Ruby 将字符串转换为方法名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8036446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby convert string to method name
提问by verdure
I have two methods defined in my ruby file.
我的 ruby 文件中定义了两种方法。
def is_mandatory(string)
puts xyz
end
def is_alphabets(string)
puts abc
end
An array containing the names of the methods.
包含方法名称的数组。
methods = ["is_mandatory", "is_alphabets"]
When I do the following
当我执行以下操作时
methods.each do |method| puts method.concat("(\"abc\")") end
It just displays, is_mandatory("abc") is_alphabets("abc") rather than actually calling the method.
它只是显示 is_mandatory("abc") is_alphabets("abc") 而不是实际调用该方法。
How can i convert the string to method name? Any help is greatly appreciated.
如何将字符串转换为方法名称?任何帮助是极大的赞赏。
Cheers!!
干杯!!
回答by Chowlett
回答by Aurril
Try using "send".
尝试使用“发送”。
methods.each do |method|
self.send(method, "abc")
end
回答by vikas95prasad
You can also add hash to send parameters to the method.
您还可以添加散列以向方法发送参数。
send("method_name", "abc", {add more parameters in this hash})
回答by Gerard Morera
All previous solutions with sendare fine but it is recommended to use public_sendinstead (otherwise you can be calling private methods).
以前的所有解决方案send都很好,但建议改用public_send(否则您可能会调用私有方法)。
Example:
例子:
'string'.public_send(:size)
=> 6

