How can a class be a class of a class and not have class instance methods?

I studied how the Ruby interpreter is interpreted, and one question arises that has not yet received an answer for me. What is indicated in the header: since Class ( r_cClass ) has super for itself (ignores metaclasses, since super is actually a metaclass r_cClass ), if I send one method to Class , this will be considered in the class table of the class' class. But Class ' class Class , so should I not look for instance methods of Class ? But this is not so, since in Class documents, Class methods and Class instance methods are separate. In search_method in eval.c Ruby, I did not find a special check for the Class Class . Can anyone shed some light on this?

+6
source share
1 answer

Your beliefs about how this works seem correct, but I'm not sure why you think this is not working.

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 regular class instance (Class.new) has 36 instance methods. If I look at the class itself, which is also an ordinary instance of the class, 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 a class automatically adds it as a class method, but adding a class to a metaclass class 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> 
+3
source

Source: https://habr.com/ru/post/898008/


All Articles