2

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.

1
  • Here's a hint: if you call 'Hello'.upcase, where would you look for the upcase method … in the string 'Hello' or in its class (String) and its superclasses? Now, if you call Object.const_set, where would you look for the const_set method … in the class Object or in its class (Class) and its superclasses? Commented Jul 19, 2016 at 8:04

3 Answers 3

2

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.superclass #=> Module

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's clear. Ruby is a really astonishing language to me.
1

In ruby, basically every class is an instance of the Class class and every class is a subclass of Object. And both Object and Class are classes. If you do

Object.is_a?class 
Class.is_a?class

In both cases, you will get a true value. Class has Module as one of the ancestor, therefore, you can use

Object.const_set("FOO", 40) 

Comments

0

There is also #ancestors to give you some more context on the object model.

> Module.ancestors
=> [Module, Object, PP::ObjectMixin, Kernel, BasicObject]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.