In Ruby, the "array.map(&:name)
" syntax consists of:
- Unary Ampersand Operator (
&
), and; - 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:
map
— calls ":name
" method on every element of the array;:name
— is the method name (matching theSymbol
) to be called on every element of array;:name.to_proc
— convertsSymbol
to a proc;&
— 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.