Flowdock
method

returning

Importance_3
v2.1.0 - Show latest stable - 2 notes - 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']
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