Allan Grant Allan Grant - 1 month ago 6x
Ruby Question

Ruby ampersand colon shortcut

Possible Duplicate:

What does map(&:name) mean in Ruby?

In Ruby, I know that if I do:


It's the same as

some_objects.each { |obj| }

That is,
creates the block
{ |obj| }
, turns it into a Proc, and passes it to each. Why does this work? Is it just a Ruby special case, or is there reason why this works as it does?


Your question is wrong, so to speak. What's happening here isn't "ampersand and colon", it's "ampersand and object". The colon in this case is for the symbol. So, there's & and there's :foo.

The & calls to_proc on the object, and passes it as a block to the method. In Rails, to_proc is implemented on Symbol, so that these two calls are equivalent:

something {|i| }

Also, to_proc on Symbol is implemented in Ruby 1.8.7 and 1.9, so it is in fact a "ruby thing".

So, to sum up: & calls to_proc on the object and passes it as a block to the method, and Ruby implements to_proc on Symbol.