In Ruby, "&:
" is itself not an operator but rather a combination of:
- The unary ampersand operator (
&
), and; - A Symbol name (which is prefixed with a colon).
It is commonly used as "&:name
" in code.
When used as "&:name
", the unary ampersand operator (&
) is applied to the Symbol ":name
", converting it to a Proc
internally by calling the Symbol#to_proc
method, like so:
object.method(&:symbol_name.to_proc)
The &
operator then converts the Proc
to a block, which is equivalent to the following:
object.method { | item | item.symbol_name }
Therefore, the following expressions are basically all equivalent, and can be used interchangeably to achieve the same result:
object.method(&:symbol_name) object.method(&:symbol_name.to_proc) object.method { | item | item.symbol_name }
Essentially, when the unary ampersand operator (&
) is applied to a Symbol in Ruby, it turns the Symbol into a Proc
. This allows the Symbol to be treated as if it were a method, allowing it to be used in situations where a block is expected.
This syntax is often used as a shorthand for creating a block that calls a method on each element of an Enumerable
object, passing the Symbol as the method name.
For example, you could use this shorthand syntax to quickly capitalize an array of strings:
arr = ["foo", "bar", "baz"] print arr.map(&:capitalize) #=> ["Foo", "Bar", "Baz"]
In this case, &:capitalize
is used with the Array#map
method. It converts the Symbol :capitalize
into a Proc
that represents the method call to capitalize
on each element of the array, resulting in a new array containing capitalized strings.
Without using the "&:
" syntax, the alternative would be to use block syntax, for example, like so:
arr = ["foo", "bar", "baz"] print arr.map { | str | str.capitalize } #=> ["Foo", "Bar", "Baz"]
This post was published (and was last revised ) 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.