Ruby : What is leading ampersand ‘&’? in .map(&:id)

Your question is wrong, so to speak. What’s happening here isn’t “ampersand and colon”, it’s “ampersand and object”. The colon in this case is for the symbol. So, there’s & and there’s :foo.

The & calls to_proc on the object, and passes it as a block to the method. In Rails, to_proc is implemented on Symbol, so that these two calls are equivalent:

something {|i| i.foo }
something(&:foo)

Also, to_proc on Symbol is implemented in Ruby 1.8.7 and 1.9, so it is in fact a “ruby thing”.

So, to sum up: & calls to_proc on the object and passes it as a block to the method, and Ruby implements to_proc on Symbol.

@jobs.map(&:id)

# equivalent to
@jobs.map do |x|
  x.id
end

`&` is used to convert any object to block; we can understand it like it wraps the object with ‘do — end ‘ wrapper. In the snipped above; :id is converted to block; as ‘map’ takes a block

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s