在Ruby中使用具有方法名称的字符串调用方法 [英] Calling a Method From a String With the Method's Name in Ruby
本文介绍了在Ruby中使用具有方法名称的字符串调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
How can I do what they are talking about here, but in Ruby?
您将如何对某个对象执行功能?以及如何执行全局功能(请参阅jetxee的
How would you do the function on an object? and how would you do a global function (see jetxee's answer on the post mentioned)?
示例代码:
event_name = "load"
def load()
puts "load() function was executed."
end
def row_changed()
puts "row_changed() function was executed."
end
#something here to see that event_name = "load" and run load()
更新: 您如何了解全局方法?或我的全局功能?
UPDATE: How do you get to the global methods? or my global functions?
我尝试了此附加行
puts methods
并在未列出的地方加载和row_change.
and load and row_change where not listed.
推荐答案
直接在对象上调用函数
a = [2, 2, 3]
a.send("length")
# or
a.public_send("length")
将按预期返回3
或用于模块功能
FileUtils.send('pwd')
# or
FileUtils.public_send(:pwd)
和本地定义的方法
def load()
puts "load() function was executed."
end
send('load')
# or
public_send('load')
文档:
这篇关于在Ruby中使用具有方法名称的字符串调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文