简体   繁体   中英

How is a call to instance_methods dispatched in Ruby?

instance_methods is defined as a public instance method within the Module class. Why and how are we then able to call Object.instance_methods , which is the syntax for class method invocation?

Because instance_methods is a instance method on Module , that method can be called on any instance of the Module class or it's subclasses.

As it turns out, Object is an instance of the Class class:

Object.instance_of? Class
#=> true

And, Class is a subclass of Module :

Class < Module
#=> true

Here's a helpful chart illustrating the class hierarchy of the various objects in Ruby. Notice how Module is listed as a superclass of Class , which all Classes in Ruby are instances of:

Ruby类层次结构

View full size

It looks like a class method in this case, but in Ruby, Object is just an instance of Class, which has Module as a super class. So what looks like a class method here is actually an instance method invoke on instance Object of class Class.

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

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

This is just method invocation like any other method invocation. You are calling the method instance_methods on the object referenced by the constant Object . That object is the Object class, which is an instance of the Class class. Class is a subclass of Module , and so the Object class is an (indirect) instance of the Module class which defines the instance_methods method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM