From: "David A. Black" Date: 2005-10-14T06:47:42+09:00 Subject: Re: instance from class name? Hi -- On Fri, 14 Oct 2005, ES wrote: > David A. Black wrote: >> Hi -- >> >> On Thu, 13 Oct 2005, Alexander Lamb wrote: >> >>> Hello, >>> >>> I am new to this list (and language) but I didn't find my answer from the >>> documentation available. >>> >>> I simply would like to do something like: >>> >>> myObject = class.fromName("a_class_name").new > > Classes are stored as constants in ruby. Witness Mr. Black's solution: > >> my_object = Object.const_get("MyClass").new >> >> or some variation of that. > > That works; however, if your class name looks like SomeModule::SomeClass, > you will need to be a bit fancier because const_get only looks for constants > in the current class or module (the top-level Object instance is the > default): > > class_name.split('::').inject(Object) {|parent, obj| parent.const_get > obj}.new Like Kernel#singleton_class, this is one of those things that gets written again and again, ad hoc. I wonder if it might be a candidate for a permanent modification to const_get.... David -- David A. Black dblack@wobblini.net