From: Jim Marshall Date: 2005-06-05T22:55:25+09:00 Subject: Re: Creating objects from strings. On 2005-06-05, Bill wrote: > 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(); > One way is like: Object.const_get("MyClass").new # returns an instance of MyClass Or, if your classes are inside a module (say, "MyModule"), then MyModule.const_get("MyClass").new > 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? > klass = Object.const_get("MyClass") # Returns the class MyClass obj = klass.new # Returns an instance of MyClass There are probably other ways to do these things, but this is the one I'm familiar with.