Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a string into a method call? [duplicate]

Tags:

ruby

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
like image 268
mko Avatar asked Jun 11 '11 17:06

mko


3 Answers

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
like image 153
Lee Jarvis Avatar answered Sep 20 '22 06:09

Lee Jarvis


If you want to do a chain, can also use Object#eval

>> a  = "foo"
 => "foo" 
>> eval "a.reverse.upcase"
 => "OOF" 
like image 23
Steve Wilhelm Avatar answered Sep 22 '22 06:09

Steve Wilhelm


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)
like image 41
starfry Avatar answered Sep 24 '22 06:09

starfry