From: Christopher Date: 2005-04-30T03:36:11+09:00 Subject: Re: Creating arbitrary objects On Sat, 2005-04-30 at 03:05 +0900, James Edward Gray II wrote: > On Apr 29, 2005, at 12:38 PM, Matthew Thill wrote: > > > I've probably overlooked something, and hopefully someone can help me > > out. I want to be able to create arbitrary object from the contents of > > a string. > > > > For example, if I had the following string: > > > > classname = "Array" > > > > How can I create an Array object, knowing only that the variable > > classname held the name of some class as a string. > > You're looking for Object.const_get(): > > irb(main):003:0> class_obj = Object.const_get("Array") > => Array > irb(main):004:0> arr = class_obj.new > => [] > > Hope that helps. > > James Edward Gray II > > > If your class is nested in a module or other class, you might want to do something like: irb:0> module A irb:1> class B irb:2> class C irb:3> end irb:2> end irb:1> end => nil irb:0> classname = 'A::B::C' => "A::B::C" irb:0> klass = classname.split('::').inject(Class) do |sum, elem| irb:1* sum.const_get(elem) irb:1> end => A::B::C irb:0> klass.new => #