tags:

views:

113

answers:

3

I just read this answer http://stackoverflow.com/questions/1791639/regular-expression-in-ruby-to-convert-uppercase-title-into-lowercase/1792102#1792102.

There is the following line of code

"abc".split(/(\W)/).map(&:capitalize).join

What exactly is &:capitalize? Before I had put this into irb myself, I would have told you, it's not valid ruby syntax. It must be some kind of Proc object, because Array#map normaly takes a block. But it isn't. If I put it into irb alone, I get syntax error, unexpected tAMPER. Please enlighten me.

+1  A: 

The ampersand is syntactic sugar that does a whole bunch of code generation with the to_proc message. See http://blog.codahale.com/2006/08/01/stupid-ruby-tricks-stringto%5Fproc/

Jonathan Feinberg
+2  A: 

It's Symbol#to_proc: see http://pragdave.pragprog.com/pragdave/2005/11/symbolto%5Fproc.html

map(&:capitalize) is exactly the same as map { |x| x.capitalize }.

Grandpa
It's not exactly the same, since there is a performance impact to the former.
ScottJ
+2  A: 

foo(&a_proc_object) turns a_proc_object into a block and calls foo with that block.

foo(&not_a_proc_object) calls to_proc on not_a_proc_object and then turns the proc object returned by to_proc into a block and calls foo with that block.

In ruby 1.8.7+ and active support Symbol#to_proc is defined to return a proc which calls the method named by the symbol on the argument to the proc.

sepp2k