On May 4, 2006, at 3:01 PM, ara.t.howard / noaa.gov wrote:

> On Fri, 5 May 2006, RGR wrote:
>
>> I want to create an object from a class, but the name of that  
>> class is
>> in a variable, so the form obj=Class.new(args) can't be used. How  
>> can it
>> be done? Without using eval, because its a bit messy and unelegant.
>>
>> The equivalent of obj=$variable_with_class_name(args) in php.
>>
>> Thanks.
>> RGR
>>
>> -- 
>> Posted via http://www.ruby-forum.com/.
>>
>
>       def klass_stamp(hierachy, *a, &b)
>         ancestors = hierachy.split(%r/::/)
>         parent = Object
>         while((child = ancestors.shift))
>           klass = parent.const_get child
>           parent = klass
>         end
>         klass::new(*a, &b)
>       end
>
>       obj = klass_stamp('String', 'foobar')
>
> -a
> -- 
> be kind whenever possible... it is always possible.
> - h.h. the 14th dali lama
>

You know you can do this with inject right?

def klass_stamp(hierachy, *a, &b)
   klass = hierachy.split(/::/).inject(Object) { |parent, child|  
parent.const_get(child) }
   klass.new(*a, &b)
end