I found this code in a RailsCast:
def tag_names
@tag_names || tags.map(&:name).join(\' \')
end
What does the (&:name)
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 }
.