Forum: Ruby on Rails [C.L.R],[RoR] How I convert string to method?

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.
51cfbf34cf1f7ebb09c3a717e40c4a85?d=identicon&s=25 Peter Smith (Guest)
on 2007-02-20 09:44
(Received via mailing list)
Hi,

suppose I have 2 strings:

s1 = "hello"
s2 = "capitalize"

I want to do this:

m = s2.to_method
s1.m
=> "Hello"

I'm working on a Rails project where I want to call arbitrary methods of
a
model class.

At run-time ...
I know how to get the names of the methods,
but can't figure out how to call the corresponding methods.

How I convert string to method?

-Peter
51cfbf34cf1f7ebb09c3a717e40c4a85?d=identicon&s=25 Peter Smith (Guest)
on 2007-02-20 09:50
(Received via mailing list)
I found the answer in the Pick Axe book:

s1.send(s2.to_sym)

HTH
-Peter
15619be638a3ae3d6f86a4995c6484c1?d=identicon&s=25 Dee Zsombor (Guest)
on 2007-02-20 11:11
(Received via mailing list)
Peter Smith wrote:
>
> I'm working on a Rails project where I want to call arbitrary methods of a
> model class.

"hello".send("capitalize".to_sym)
=> "Hello"

Or probably even better __send__ instead of send.

Zsombor
--
Company  - http://primalgrasp.com
Thoughts - http://deezsombor.blogspot.com
This topic is locked and can not be replied to.