Why an Object is_a? Module?

I have a piece of code (derived from
http://stackoverflow.com/questions/5924495/how-do-i-create-a-class-instance-from-a-string-name-in-ruby),
which works like a charm, but I don’t fully understand WHY it works.
Here is a small example which describes the issue:

class MyClass
def initialize
end
def say_something
puts ‘hello’
end
end
clazzname=‘MyClass’
clazz=Object.const_get(clazzname)
x=clazz.new
x.say_something

The last line prints “hello”.

On researching the details, I found the description of the method
const_get here:

http://ruby-doc.org/core-1.8.6/Module.html#method-i-const_get

Interestingly, const_get is not a method of Object, but of Module, and
indeed, changing the code to

clazz=Module.const_get(clazzname)

works as well. I wanted to know however, why Object.const_get works too,
so I tried in irb:

irb(main):036:0> Object.is_a?(Module)
=> true

Well, this explains why the above call works. Now to the puzzling part:

http://ruby-doc.org/core-1.8.6/Module.html mentions, that the parent
class of Module is Object. Indeed, a little experimenting shows:

irb(main):050:0> Module.is_a?(Object)
=> true

This by itself is not surprising, because everything is an Object. But
why is an Object also a Module?

On Wed, Nov 20, 2013 at 10:26 AM, Ronald F. [email protected]
wrote:

why is an Object also a Module?

Object is a Module (since Object is a Class and Classes are Modules),
but an Object is not:

1.9.3-p429 :001 > Object.is_a? Module
=> true
1.9.3-p429 :002 > Object.new.is_a? Module
=> false

-Dave

Dave A. wrote in post #1128077:

Object is a Module (since Object is a Class and Classes are Modules),
but an Object is not:

Got it! Thank you for explaining!

Ronald

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs