开发者

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

开发者 https://www.devze.com 2023-03-12 19:39 出处:网络
This question already has answers here: How to call methods dynamically based on their name? [duplicate]
This question already has answers here: How to call methods dynamically based on their name? [duplicate] (5 answers) Closed 8 years ago.

How can I use a string a开发者_如何学运维s 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消