method

returning

v2.0.3 - Show latest stable - Class: Object
returning(value)
public

A Ruby-ized realization of the K combinator, courtesy of Mikael Brockman.

  def foo
    returning values = [] do
      values << 'bar'
      values << 'baz'
    end
  end

  foo # => ['bar', 'baz']

  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