What exactly is `&:capitalize` in Ruby?

Solution 1:

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.

Solution 2:

It's Symbol#to_proc: see http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html

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

Solution 3:

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_proc/