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

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

    (&:name) is short for (&:name.to_proc) it is same as tags.map{ |t| t.name }.join(' ')

    to_proc is actually implemented in C

    0 讨论(0)
  • 2020-11-21 06:02
    tags.map(&:name)
    

    is The same as

    tags.map{|tag| tag.name}
    

    &:name just uses the symbol as the method name to be called.

    0 讨论(0)
  • 2020-11-21 06:02

    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 }.

    0 讨论(0)
  • 2020-11-21 06:03

    It's shorthand for tags.map { |tag| tag.name }.join(' ')

    0 讨论(0)
  • 2020-11-21 06:04

    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
    
    0 讨论(0)
  • 2020-11-21 06:04

    It is same as below:

    def tag_names
      if @tag_names
        @tag_names
      else
        tags.map{ |t| t.name }.join(' ')
    end
    
    0 讨论(0)
提交回复
热议问题