I found this code in a RailsCast:
def tag_names
@tag_names || tags.map(&:name).join(\' \')
end
What does the (&:name)
(&:name) is short for (&:name.to_proc) it is same as tags.map{ |t| t.name }.join(' ')
to_proc is actually implemented in C
tags.map(&:name)
is The same as
tags.map{|tag| tag.name}
&:name
just uses the symbol as the method name to be called.
First, &:name
is a shortcut for &:name.to_proc
, where :name.to_proc
returns a Proc
(something that is similar, but not identical to a lambda) that when called with an object as (first) argument, calls the name
method on that object.
Second, while &
in def foo(&block) ... end
converts a block passed to foo
to a Proc
, it does the opposite when applied to a Proc
.
Thus, &:name.to_proc
is a block that takes an object as argument and calls the name
method on it, i. e. { |o| o.name }
.
It's shorthand for tags.map { |tag| tag.name }.join(' ')
Here :name
is the symbol which point to the method name
of tag object.
When we pass &:name
to map
, it will treat name
as a proc object.
For short, tags.map(&:name)
acts as:
tags.map do |tag|
tag.name
end
It is same as below:
def tag_names
if @tag_names
@tag_names
else
tags.map{ |t| t.name }.join(' ')
end