benjohn
3/18/2006 12:46:00 AM
On 17 Mar 2006, at 05:01, Kev Jackson wrote:
> Gaudi Mi wrote:
>
>> At runtime I have the name of a class in a string, and I want to
>> call a method on the class having that name. How do I do that?
>>
>> E.g., let's say that we have several classes that all have a
>> method called address().
>> At run-time I know I want to call the method address() on a
>> particular class, and that class name is in a string.
>>
> you need to look at call
>
> eg to instantiate an object (call Object.new)
>
> m = c.method(:new)
> o = m.call
I don't think that's going to work for him (if c is the
name_of_class_string that he's got). He needs to look up the class
named name_of_class_string:
ObjectSpace.const_get(name_of_class_string).new(*any_arguments)
I'd like to check that is the "right way" to do it, but I don't have
any reference books to hand.