Coda Chang Coda Chang - 4 months ago 7
Ruby Question

Ruby Object and Module

I'm confused about these two class when I was reading Module document.
First of all, I saw there is a way to set the named constant to the given object.

Object.const_set("FOO", 40)


But I check ruby doc, there is no
const_set
in Object method, then I found out it was defined in Module.

I thought
Object
is the default root of all Ruby objects. Why it can use module method? I am confused about the relationship between those.

Answer

As shown below :const_set is an instance method stored in Module:

Module.instance_methods(false).include? :const_set #=> true

Also note that Object is an instance of Class:

Object.instance_of? Class #=> true

And Class is a subclass of Module:

Class.ancestors #=> [Class, Module, Object, Kernel, BasicObject]

All of this means that instance methods defined within Module are available to Class objects via inheritance. So any instance of Class (such as Object) has at its disposal all the instance methods (including :const_set) stored in Module.

Comments