map(&:name) 在 Ruby 中是什么意思? [英] What does map(&:name) mean in Ruby?
本文介绍了map(&:name) 在 Ruby 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 a RailsCast 中找到了此代码:
I found this code in a RailsCast:
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
map(&:name)
中的 (&:name)
是什么意思?
What does the (&:name)
in map(&:name)
mean?
推荐答案
它是 tags.map(&:name.to_proc).join(' ')
如果 foo
是一个带有 to_proc
方法的对象,那么你可以将它作为 &foo
传递给一个方法,它会调用foo.to_proc
并将其用作方法的块.
If foo
is an object with a to_proc
method, then you can pass it to a method as &foo
, which will call foo.to_proc
and use that as the method's block.
Symbol#to_proc
方法最初由 ActiveSupport 添加,但已集成到 Ruby 1.8.7 中.这是它的实现:
The Symbol#to_proc
method was originally added by ActiveSupport but has been integrated into Ruby 1.8.7. This is its implementation:
class Symbol
def to_proc
Proc.new do |obj, *args|
obj.send self, *args
end
end
end
这篇关于map(&:name) 在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文