How can I use a string as a method call?
"Some Word".class #=> String
a = "class"
"Some World".a #=> undefined method 'a'
"Some World"."#{a}" #=> syntax error, unexpected tSTRING_BEG
Object#send
>> a = "class"
>> "foo".send(a)
=> String
>> a = "reverse"
>> "foo".send(a)
=> "oof"
>> a = "something"
>> "foo".send(a)
NoMethodError: undefined method `something' for "foo":String
If you want to do a chain, can also use Object#eval
>> a = "foo"
=> "foo"
>> eval "a.reverse.upcase"
=> "OOF"
If you have a string that contains a snippet of ruby code, you can use eval
. I was looking for question with that answer when I landed here. After going off and working it out (thanks ProgrammingRuby), I'm posting this in case others come here looking for what I was looking for.
Consider the scenario where I have a line of code. here it is:
NAMESPACE::method(args)
Now consider the scenario where that is in a string variable
myvar = "NAMESPACE::method(args)"
Using send(myvar)
does not execute the command. Here is how you do it:
eval(myvar)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With