From: Nicholas Seckar Date: 2005-06-06T02:34:52+09:00 Subject: Re: Creating objects from strings. Bill wrote: > > 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") > This is an excellent place to use inject: def load(filename, classname) require filename classname.split('::').inject(Object) {|module, name| module.const_get name}.new end You might also like to know that const_get will look in the parent modules as well. For example, module A module B end end A.constants #=> ['B'] A.const_get :Object #=> Object A::Object #=> Unitialized constant A::Object Because of this I've resorted to using eval "#{module}::#{name}" -- Does anyone know of a non-eval way of doing this? And, as you may or may not know, Ruby comes with a load method, so you might want to change your method name to load_instance or something.