I found this code in a RailsCast:
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
What does the (&:name)
in map(&:name)
mean?
I found this code in a RailsCast:
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
What does the (&:name)
in map(&:name)
mean?
While let us also note that ampersand
#to_proc
magic can work with any class, not just Symbol. Many Rubyists choose to define#to_proc
on Array class:Ampersand
&
works by sendingto_proc
message on its operand, which, in the above code, is of Array class. And since I defined#to_proc
method on Array, the line becomes:Although we have great answers already, looking through a perspective of a beginner I'd like to add the additional information:
This means, that you are passing another method as parameter to the map function. (In reality you're passing a symbol that gets converted into a proc. But this isn't that important in this particular case).
What is important is that you have a
method
namedname
that will be used by the map method as an argument instead of the traditionalblock
style.it means
Another cool shorthand, unknown to many, is
which is a shorthand for
By calling
method(:foo)
we took aMethod
object fromself
that represents itsfoo
method, and used the&
to signify that it has ato_proc
method that converts it into aProc
.This is very useful when you want to do things point-free style. An example is to check if there is any string in an array that is equal to the string
"foo"
. There is the conventional way:And there is the point-free way:
The preferred way should be the most readable one.
Here
:name
is the symbol which point to the methodname
of tag object. When we pass&:name
tomap
, it will treatname
as a proc object. For short,tags.map(&:name)
acts as:map(&:name) takes an enumerable object (tags in your case) and runs the name method for each element/tag, outputting each returned value from the method.
It is a shorthand for
which returns the array of element(tag) names