5

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
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
mko
  • 21,334
  • 49
  • 130
  • 191

3 Answers3

16

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
Lee Jarvis
  • 16,031
  • 4
  • 38
  • 40
  • 2
    You can also add arguments to send: `"foo".send("<<", "bar")`. – Guilherme Bernal Jun 11 '11 at 18:44
  • thanks for your quick answer, the the link to the document, I'm wandering how you guy put the this links there, is there any short cut to do these kind of thing? – mko Jun 13 '11 at 15:15
  • @yozloy Stack Overflow uses Markdown so you can use \[some text](some link) to format links. If you want more information, click the 'help' button next to the comment box or see [here](http://stackoverflow.com/editing-help) – Lee Jarvis Jun 13 '11 at 16:29
  • I am getting `in send: wrong number of arguments (1 for 0)` when I pass the command into the send function. Your code work,s but when I try and call something like `ExampleClass.new.send("function")` I get that error. – Jon Doe May 16 '15 at 15:17
  • @ChristianJuth Can you provide a full example? – Lee Jarvis May 18 '15 at 11:09
1

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)
starfry
  • 9,273
  • 7
  • 66
  • 96
1

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

>> a  = "foo"
 => "foo" 
>> eval "a.reverse.upcase"
 => "OOF" 
Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36