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

2018-12-31 01:03发布

I found this code in a RailsCast:

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

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

14条回答
旧时光的记忆
2楼-- · 2018-12-31 01:33

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

to_proc is actually implemented in C

查看更多
墨雨无痕
3楼-- · 2018-12-31 01:34
tags.map(&:name)

is The same as

tags.map{|tag| tag.name}

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

查看更多
登录 后发表回答