Forum: Ruby on Rails Invoking a method by name

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Robert W. (Guest)
on 2007-03-26 22:27
(Received via mailing list)
Hello all,

I have a need to invoke methods dynamically by name.

Say I have a method like:

def invoke_method_with_name(method_name)
  person = Person.find(params[:id])
  method_to_invoke = ~~ some code to find the method from a string
containing the method name ~~
  person.method_to_invoke
end

I do this in Objective C with something like the following:

SEL  setWidthHeight;
setWidthHeight = @selector(setWidth:height:);
or
setWidthHeight = NSSelectorFromString(aBuffer);

Where SEL is a special type representing an Objective C method
signature, and the @selector directive or
NSSelectorFromString(aBuffer) is used to find the method.

I have a feeling that I'm making this more complicated than need be.

Is it possible to do something as simple as:

person.#{method_to_invoke}
Philip H. (Guest)
on 2007-03-26 22:33
(Received via mailing list)
>
>
> I have a feeling that I'm making this more complicated than need be.
>
> Is it possible to do something as simple as:
>
> person.#{method_to_invoke}

You want send()...

http://www.ruby-doc.org/core/classes/Object.html#M000334
Robert W. (Guest)
on 2007-03-26 22:41
(Received via mailing list)
Philip,

Excellent, that's just what I was looking for.
This topic is locked and can not be replied to.