method

returning

Importance_3
Ruby on Rails latest stable (v6.1.7.7) - 2 notes - 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.

These similar methods exist in v6.1.7.7:

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']
Show source
Register or log in to add new notes.
January 8, 2009
5 thanks

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
July 23, 2012
0 thanks

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