Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby : `&:symbol` syntax [duplicate]

Tags:

ruby

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

In Ruby, I know that if I do:

some_objects.each(&:foo)

It's the same as

some_objects.each { |obj| obj.foo }

That is, &:foo creates the block { |obj| obj.foo }, 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?

like image 959
Allan Grant Avatar asked Dec 25 '09 11:12

Allan Grant


1 Answers

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 Ruby, to_proc is implemented on Symbol, so that these two calls are equivalent:

something {|i| i.foo }
something(&:foo)

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.

like image 186
August Lilleaas Avatar answered Sep 22 '22 04:09

August Lilleaas