From: Alexander Lamb Date: 2005-10-14T04:44:11+09:00 Subject: Re: instance from class name? Thanks for those pointers. The first suggestion worked and since I can trust the String of the name of the class, it is ok. However, I didn't find it in the documentation of the Object class. I started on ruby-lang.org then was brought to rubycentral for the reference. Is there another complete reference for ruby 1.8.x? (I am running on MacOSX 10.4.2). Thanks, -- Alexander Lamb Service d'Informatique M�dicale H�pitaux Universitaires de Gen�ve Alexander.J.Lamb@sim.hcuge.ch +41 22 372 88 62 +41 79 420 79 73 On Oct 13, 2005, at 9:13 PM, 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 > > #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 > > > >