From: Bill Date: 2005-06-06T02:15:25+09:00 Subject: Re: Creating objects from strings. On 2005-06-05 09:51:42 -0400, James Britt said: > 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(); > > > mc = Object.const_get( "MyClass" ).new > > This presumes that the code already knows about the class MyClass > (e.g., because the class is defined in the same file, or defined in a > file that has already been read using 'require' or 'load'). > > > > BTW, I looked at the Ruby FAQ, and this question doesn't seem to be in > there, despite its popularity. > > http://dev.rubycentral.com/faq/ > > > > James Thanks for all the quick help. The presumption was my problem. I had some code that I got that should have worked, but wasn't requiring the file. I'm now able to create classes from external files/modules with the following. def load (filename, classname) require filename # taken from http://www.ruby-talk.org/cgi-bin/scat.rb/ruby/ruby-talk/9295 names = classname.split /::/ names.reverse! unf = Object unf = unf.const_get(names.pop) while names.length > 0 unf.new end load ("myfile.rb", "myModule::myClass")