Code introspection

Sounds like what you need is to get the corresponding Class object for
the class given the string name. All class names are constants of
Object:

irb(main):001:0> class MyClass;end
=> nil
irb(main):002:0> k = Object.const_get 'MyClass'
=> MyClass
irb(main):003:0> k.class
=> Class
irb(main):004:0> k_instance = k.new
=> #<MyClass:0x2b80218>
irb(main):006:0> k_instance.class
=> MyClass
irb(main):007:0>

HTH,
Assaph

···

-----Original Message-----
From: Daniel Cremer [mailto:daniel@danielcremer.com]
Sent: Monday, 26 July 2004 8:22 PM
To: ruby-talk ML
Subject: code introspection

Hi,

Is there a solution to do code introspection rather than introspection
at the level of the Module/Object ? I can't figure out if I'm looking
for something that isn't there in Ruby since I've been reading C# code
or if I'm missing something. Let me explain my problem.
I would like to load ruby source files and dynamically create objects
from classes located inside these sources. It's one class/object per
source file and I can make it so that a string from a configuration
file holds the name of the class. However I can't figure out a good way
to use that string to get to the class in the source file.

I could use eval but am really uncomfortable with that for obvious
reasons (people keep saying it's evil so I don't play with him). The
other solution I came up with was to add a method in the same source but
outside the class to return the desired object:

--------------source file---------
class MyNewClass
....
end

def create_loaded_class()
  return MyNewClass.new()
end
---------------------------------

Then as I require the source files I can successively invoke the
create_loaded_class method. This works but can get quite messy as there
are a lot of things to consider if you need to reload sources and create
new objects etc.
Please tell me I'm missing something obvious :).

thanks,
Daniel