August 27, 2009

ruby block syntax

Reading a commit from DHH I found out a syntax I was not aware of.

Instead of doing:

[1,2,3,4,5,6,7,8,9,10].select { |x| x.even? }

You can do:

[1,2,3,4,5,6,7,8,9,10].select(&:even?)

When I asked in #rubyonrails irc channel about this syntax, I got enlightened: The first part is obvious: last argument starting with & is interpreted as a Proc and equivalent to passing a block, so it is not a &: operator but & and a symbol. How does the symbol work?

According to the people in the channel, it is rails magic. When I said that it works for me in irb I was told I must be running ruby 1.9, which I am not. After some discussion we realized this magic is in ruby 1.8.7 too.

The magic is of course, just Symbol#to_proc method ;-)

Leave a Reply