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

后端 未结 16 2507
时光取名叫无心
时光取名叫无心 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:10

    Another cool shorthand, unknown to many, is

    array.each(&method(:foo))
    

    which is a shorthand for

    array.each { |element| foo(element) }
    

    By calling method(:foo) we took a Method object from self that represents its foo method, and used the & to signify that it has a to_proc method that converts it into a Proc.

    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:

    ["bar", "baz", "foo"].any? { |str| str == "foo" }
    

    And there is the point-free way:

    ["bar", "baz", "foo"].any?(&"foo".method(:==))
    

    The preferred way should be the most readable one.

提交回复
热议问题