Ruby 中的匿名类
我有两个问题:
- 方法
f_1
是否属于元类匿名类? - 方法
f_2
属于匿名类吗?
与以下代码相关:
car = "car"
class << car
def self.f_1
puts "f_1"
end
def f_2
puts "f_2"
end
end
I have two questions:
- Does method
f_1
belong to the metaclass anonymous class? - Does method
f_2
belong to the anonymous class?
related to the following code:
car = "car"
class << car
def self.f_1
puts "f_1"
end
def f_2
puts "f_2"
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于 ruby 自己的 API 使用术语“单例类”,我可以说以下内容是正确的:
f_1
是汽车单例类的类方法,可以像这样调用:<前><代码>car.singleton_class.f_1
f_2
是 car 单例类的实例方法可以这样调用:<前><代码>car.f_2
Since ruby's own API uses the term "singleton class," I'd say the following are true:
f_1
is a class method on car's singleton class and can be called like this:f_2
is an instance method on car's singleton class and can be called like this:好吧,术语很脆弱,但FWIW我想说你的班级并不是真正的匿名班级。至于归属感,这两个方法都只存在于 car 对象中。
我会诚实地承认,当类是针对像这样的单个对象定义的时,我对类方法和实例方法之间的区别有点模糊——我猜如果有任何区别,它会是一个晦涩的代码,会让你的代码更难阅读;)
更新:你可能会发现这个 有帮助,如果你有以前没见过。 (就我个人而言,这让我很头疼,但每个人都不一样......)
Well, terminology is frangible, but FWIW I would say your class wasn't really an anonymous class. As for belonging, both of these methods only exist in the car object.
I'll be honest and admit that I'm a little vague about the difference between a class method and an instance method when the class is defined against an individual object like this -- I would guess that if there is any difference, it will be an obscure one that will make your code much harder to read ;)
Update: You might find this helpful, if you've not seen it before. (Personally, it makes my head hurt, but everyone's different...)
我的印象是匿名类是没有名称的类:
但是,Pickaxe 将其称为未命名类而不是匿名类。
I was under the impression that an anonymous class is a class that has no name:
However, the Pickaxe refers to it as a unnamed class rather than as an anonymous class.
Rob Davis 答案的重新表述:
:f_1
的方法所有者是car.singleton_class.singleton_class
。:f_2
的方法所有者是car.singleton_class
。链
car
→car.singleton_class
→car.singleton_class.singleton_class
对应于图中 http://www.atalon.cz/rb-om/ruby-object-model/#sc-inheritance-sample。注意:
A reformulation of Rob Davis' answer:
:f_1
iscar.singleton_class.singleton_class
.:f_2
iscar.singleton_class
.The chain
car
→car.singleton_class
→car.singleton_class.singleton_class
corresponds to the bottom row in the diagram at http://www.atalon.cz/rb-om/ruby-object-model/#sc-inheritance-sample.Notes: