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?
···
--
Posted via http://www.ruby-forum.com/.