Le 5/6/2005, "Bill" <ruby / thebackfamily.com> a ˝─rit:
>Hi,
>
>I'm a Java programmer that is trying to learn Ruby.
>
>I'm trying to write a container that creates objects on the fly from a
>descriptor.  In Java I'd simply do
>Class.forName("MyClass").newInstance();
>
>Is there an easy way to do this in Ruby?  I basically want a loader
>that I can call Loader.createObject(filename, classname) where filename
>is the name of the ruby file containing the class and classname is the
>actual class.
>
>Also, since I'll be creating more than one instance of each class, how
>do I store the class instance?

You can always eval:  obj = eval(classname).new, but this is cleaner:

cls = const_get classname
obj = cls.new

If you know the class is in some namespace (or other module):

cls = ModuleName.const_get classname

>TIA.
>
>Bill.

E

--
template<typename duck>
void quack(duck& d) { d.quack(); }