How is access to instances of instance_methods called in Ruby?

instance_methods

defined as a public instance method in the class Module

. Why and how can we then call Object.instance_methods

, which is the syntax for calling a class method?

+3


source to share


3 answers


Because it instance_methods

is an instance method in Module

, this method can be called on any instance of the class Module

or subclasses.

As it turned out, it Object

is an instance of the class Class

:

Object.instance_of? Class
#=> true

      

And, Class

is a subclass Module

:



Class < Module
#=> true

      

Here is a helpful diagram illustrating the class hierarchy of various objects in Ruby. Note that it Module

is listed as a superclass from Class

which all classes in Ruby are instances:

Ruby class hierarchy

Show in original size

+4


source


In this case, it is similar to a class method, but in Ruby Object is just an instance of a class that has a module as a superclass. So what looks like a class method here is actually an instance method called on the Object Object of the Class class.



Object.instance_of? Class # => true
Object.is_a? Module #=> true 

      

0


source


There is no such thing as "class method invocation syntax". There is also no such thing as a "class method".

It's just a method call just like any other method call. You are calling a method on the instance_methods

object that the constant refers to Object

. This object is a class Object

that is an instance of the class Class

. Class

is a subclass Module

, so a class Object

is an (indirect) instance of the class Module

that defines the method instance_methods

.

0


source







All Articles