From: James Edward Gray II Date: 2006-04-29T02:45:31+09:00 Subject: Re: how to create Class object with name determined at runtime On Apr 28, 2006, at 12:36 PM, Bill Roberts wrote: > I hope someone can help with this - I am a Ruby newbie. > > In my code I want to decide at runtime which type of object to create, > based on a variable holding the name of the class. > > So I have classes Foo and Bar and a string todays_class. > > If todays_class = "Foo" I want to say my_obj = Foo.new > if todayS_class = "Bar" then my_obj = Bar.new > > Except I've got a lot more than two classes and I'd prefer not to > use an > if or case statement, so that I don't need to change the code if I add > another one to the list. > > Any suggestions on a neat way to do this? >> class Foo; end => nil >> class Bar; end => nil >> cls = "Foo" => "Foo" >> Object.const_get(cls) => Foo >> # Or, for nested classes... ?> class Foo >> class Baz; end >> end => nil >> cls = "Foo::Baz" => "Foo::Baz" >> cls.split("::").inject(Object) do |parent, constant| ?> parent.const_get(constant) >> end => Foo::Baz Hope that helps. James Edward Gray II