开发者

How can Class be of the Class class and not have Class instance methods?

I was studying how the Ruby interpreter is implemented, and one question occurred that didn't get an answer yet for me. That's the one in the title: since Class (r_cClass) has super set to itself (ignoring metaclasses, since actually super is the metaclass of r_cClass), if I send one method to the Class object, this will be looked in the method table of Class' class. But Class' class is Class, so shouldn't I end up looking the开发者_C百科 instance methods of Class? But that's not the case since in the documentation Class class methods and Class instance methods are separated. In the search_method in eval.c of Ruby, I didn't find any special check for the Class class. Can anyone shed some light on this?


Your beliefs about the way it should work seem right, but I'm not sure why you think it doesn't work that way.

In Ruby 1.8.7:

irb> a = Class.new.methods - Object.new.methods
=> [... 36 element array ...]
irb> b = Class.methods - Object.new.methods
=> [... 37 element array ...]
irb> b - a
=> ["nesting"]

A normal class instance (Class.new) has 36 instance methods. If I look at Class itself, which is also a normal class instance, it has the same 36 instance methods, plus 1 additional class method (nesting), which exists only because it is inherited from its superclass Module.

Note that adding an instance method to Class automatically adds it as a class method as well, but adding a class to Class's metaclass will not.

irb> class Class ; def everywhere ; true ; end ; end
irb> class << Class ; def only_singleton ; true ; end ; end
irb> Class.everywhere
=> true
irb> Class.new.everywhere
=> true
irb> Class.only_singleton
=> true
irb> Class.new.only_singleton
NoMethodError: undefined method 'only_in_singleton' for #<Class:0x4800ac8>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜