What Does the Array "map(&:name)" Syntax Mean in Ruby?

Find out what the "map(&:name)" syntax is meant for in Ruby

In Ruby, the "array.map(&:name)" syntax consists of:

  1. Unary Ampersand Operator (&), and;
  2. Symbol (e.g. :name).

You can use this syntax to call a method "name" (matching the Symbol, ":name") on every item of an array.

For example, you could use this to quickly convert an array of numeric strings to an array of integers (using the String#to_i method):

["1", "2", "3"].map(&:to_i)
#=> [1, 2, 3]

You could also use this shorthand syntax to quickly capitalize an array of strings:

["foo", "bar", "baz"].map(&:capitalize)
#=> ["Foo", "Bar", "Baz"]

This syntax is also known as "pretzel colon". When used with Array#map or Array#map! (e.g. array.map(&:name)), this syntax is meant as a shorthand for:

array.map(&:name.to_proc)

It can be broken down as follows:

  1. map — calls ":name" method on every element of the array;
  2. :name — is the method name (matching the Symbol) to be called on every element of array;
  3. :name.to_proc — converts Symbol to a proc;
  4. &converts proc to a block.

This conversion from Symbol to block is important as Array#map (and Array#map!) uses blocks. After the conversions are made, you get a syntax equivalent to the following:

array.map { |item| item.name }

Hope you found this post useful. It was published . Please show your love and support by sharing this post.