AbstractBrain Answers About us →

What does map(&:name) mean in Ruby?

Question

What does map(&:name) mean in Ruby?

@users.map(&:name)

In the above code, what does the &:name means?

Answer

The syntax &:name in Ruby is just syntactic sugar:

@users.map(&:name)

# is equivalent to

@users.map { |u| u.name }

&:name creates a block that receives an object and calls the #name method on it.

Basically in the above code you have an array of users and you get an array of strings with only the names of the users.