I have a piece of code (derived from
How do I create a class instance from a string name in ruby? - Stack Overflow),
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:
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:
Class: Module (Ruby 1.8.6) 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?