理解 [ClassOne, ClassTwo].each(&:my_method) [英] Understanding [ClassOne, ClassTwo].each(&:my_method)
本文介绍了理解 [ClassOne, ClassTwo].each(&:my_method)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
map(&:name) 在 Ruby 中是什么意思?
我正在看一个 railscast,看到了这段代码.
I was watching a railscast and saw this code.
[Category, Product].(&:delete_all)
关于清除数据库.
我询问了 IRC 中的线路并被告知
I asked about the line in IRC and was told
(&:delete_all)
是
{|model| model.delete_all}
我使用以下方法对此进行了测试
I tested this with the following
class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
我收到一条错误消息
Wrong Argument type Symbol (expected Proc)
我也试过
one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
但还是失败了.
如果我修改为阅读
[one, two].each{|model| model.class_method}
一切都按预期进行.
那么,&:delete_all
实际上是做什么的?文档说 delete_all
是一种方法,所以我对这里发生的事情感到困惑.
So, what does &:delete_all
actually do? The docs say delete_all
is a method, so I am confused as to what is going on here.
推荐答案
这依赖于 Ruby 1.9 扩展,该扩展可以在 1.8 中完成,包括以下内容:
This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
我相信 Rails 在 ActiveSupport
中定义了这一点.
I believe Rails defines this in ActiveSupport
.
这篇关于理解 [ClassOne, ClassTwo].each(&:my_method)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文