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

后端 未结 16 2545
时光取名叫无心
时光取名叫无心 2020-11-21 05:34

I found this code in a RailsCast:

def tag_names
  @tag_names || tags.map(&:name).join(\' \')
end

What does the (&:name)

16条回答
  •  终归单人心
    2020-11-21 06:14

    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

    array.map { |element| element.name }
    

    which returns the array of element(tag) names

提交回复
热议问题