method

returning

rails latest stable - Class: Object

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v3.0.9) is shown here.

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

Mange · Jan 8, 20095 thanks

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

kamilio · Jul 23, 2012

==== 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