44

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

Post.all.map(&:id) 

will return

 => [1, 2, 3, 4, 5, 6, 7, ................] 

What does map(&:id) mean? Especially the &.

1
  • 1
    thanks for closed as exact duplicate. This question is a little hard for search. Sorry.
    – hey mike
    Feb 27, 2012 at 16:59

4 Answers 4

85

The & symbol is used to denote that the following argument should be treated as the block given to the method. That means that if it's not a Proc object yet, its to_proc method will be called to transform it into one.

Thus, your example results in something like

Post.all.map(&:id.to_proc)

which in turn is equivalent to

Post.all.map { |x| x.id }

So it iterates over the collection returned by Post.all and builds up an array with the result of the id method called on every item.

This works because Symbol#to_proc creates a Proc that takes an object and calls the method with the name of the symbol on it. It's mainly used for convenience, to save some typing.

4
  • 5
    This is not true. map(:id.to_proc) will throw an ArgumentError because map accepts no arguments. Passing a Proc as an argument is not the same as supplying a block. What & does is it turns a Proc into a block and if the operand is not a Proc it calls to_proc first and then turns the result into a block.
    – sepp2k
    Feb 27, 2012 at 16:43
  • @sepp2k: Yeah, I forgot an & there.
    – Niklas B.
    Feb 27, 2012 at 16:44
  • Your first sentence should also read something like "&x is the same as &x.to_proc" - except that definition is infinitely recursive.
    – sepp2k
    Feb 27, 2012 at 16:46
  • @sepp2k: I already removed that part.
    – Niklas B.
    Feb 27, 2012 at 16:47
6

& means that you are passing a block

Post.all is the receiver of the method .map, and its block is being passed on

Post.all.map { |item| # do something }

http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map

It iterates over the array and create a lambda with symbol#to_proc

http://ruby-doc.org/core-1.9.3/Symbol.html#method-i-to_proc

3

This takes all Post objects and creates an array with the id method being invoked on each one.

In other words, for ActiveRecord, this means that you are getting an array with the id attribute for all Post entities in your database.

1

It is a Ruby trick, which relies on Ruby doing some dynamic type conversion. You can find an explanation of the Symbol#to_proc trick here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.