Reputation: 53
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?
Upvotes: 4
Views: 670
Reputation: 48418
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:
Upvotes: 5
Reputation: 369526
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.
Upvotes: 0
Reputation: 526
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
Upvotes: 0