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.
21f7ed21f11a809050594c82eab11d67?d=identicon&s=25 Robert Walker (Guest)
on 2007-03-26 20: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}
2f9a03aa0fcfe945229cb6126eda2cb2?d=identicon&s=25 Philip Hallstrom (Guest)
on 2007-03-26 20: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
21f7ed21f11a809050594c82eab11d67?d=identicon&s=25 Robert Walker (Guest)
on 2007-03-26 20: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.