What Does the Array "map(&:name)" Syntax Mean 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:


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 }

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.