5

I just read this answer Converting upper-case string into title-case using Ruby.

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.

Community
  • 1
  • 1
johannes
  • 7,262
  • 5
  • 38
  • 57
  • The reason it doesn't work in irb for you is probably because, like sepp2k says, it was only baked into the standard library in Ruby 1.8.7, and I'm guessing you're running an earlier version. You see it pretty frequently, though, because ActiveSupport also throws it in, and ActiveSupport comes with Rails. If you try it in Rails' script/console you'll probably discover it works. – Jordan Running Nov 24 '09 at 20:40
  • possible duplicate of [What does map(&:name) mean in Ruby?](http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby) – Jörg W Mittag Dec 22 '10 at 22:27

3 Answers3

6

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
  • 363,768
  • 54
  • 674
  • 675
5

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 }.

Grandpa
  • 3,053
  • 1
  • 25
  • 35
1

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/

Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103