method
returning
rails latest stable - Class:
Object
returning(value)public
Returns value after yielding value to the block. This simplifies the process of constructing an object, performing work on the object, and then returning the object from a method. It is a Ruby-ized realization of the K combinator, courtesy of Mikael Brockman.
Examples
# Without returning def foo values = [] values << "bar" values << "baz" return values end foo # => ['bar', 'baz'] # returning with a local variable def foo returning values = [] do values << 'bar' values << 'baz' end end foo # => ['bar', 'baz'] # returning with a block argument def foo returning [] do |values| values << 'bar' values << 'baz' end end foo # => ['bar', 'baz']
2Notes
Watch out for syntax errors
Watch out when you are using +returning+ with hashes. If you would write code like def foo(bars) returning {} do |map| bars.each { |bar| map[bar.first] = bar } end end you will get a syntax error since it looks like you tried to supply two blocks! Instead you should write it with parenthesis around the hash: def foo(bars) returning({}) do |map| bars.each { |bar| map[bar.first] = bar } end end
Replacement
==== Replacement
# Method using returning can replaced
def foo
returning Hash.new do |h|
h[:foo] = "bar"
end
end
# By method using tap
def foo
Hash.new.tap do |h|
h[:foo] = "bar"
end
end