From: ES Date: 2005-10-14T04:13:40+09:00 Subject: Re: instance from class name? 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 #split creates an array ['SomeModule', 'SomeClass'], which we iterate over using #inject. In the #inject block, the parent will always be the parent class or module in which we look for the constant and obj is the next class or module name. The Object is passed in as the initial parent object. the parent.const_get obj sequence then looks like Object.const_get 'SomeModule' => => SomeModule.const_get 'SomeClass' There may be a method to directly get the class in the future whether it is nested or not. In the meanwhile, you can stick the above code in a method if you will be using it a lot. Also, you can always use #eval: obj = eval(class_name).new Only, of course, if you trust the source of the class_name String. The former method is preferred, though. > David E