我怎么才能做到他们所说的here,而不是Ruby语言?
您将如何在对象上执行该函数?你将如何做一个全局函数(参见jetxee的answer )?
示例代码:
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()
更新:如何获取全局方法?还是我的全局函数?
我试过了这一行
puts methods
以及未列出的load和row_change。
发布于 2009-09-10 20:17:27
直接在对象上调用函数
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')
文档:
发布于 2015-08-08 21:09:26
三种方式:send
/ call
/ eval
-及其基准测试
典型调用(供参考):
s= "hi man"
s.length #=> 6
使用send
s.send(:length) #=> 6
使用call
method_object = s.method(:length)
p method_object.call #=> 6
使用eval
eval "s.length" #=> 6
基准测试
require "benchmark"
test = "hi man"
m = test.method(:length)
n = 100000
Benchmark.bmbm {|x|
x.report("call") { n.times { m.call } }
x.report("send") { n.times { test.send(:length) } }
x.report("eval") { n.times { eval "test.length" } }
}
你可以看到,实例化一个方法对象是调用一个方法的最快的动态方式,还要注意使用
的速度有多慢。
#######################################
##### The results
#######################################
#Rehearsal ----------------------------------------
#call 0.050000 0.020000 0.070000 ( 0.077915)
#send 0.080000 0.000000 0.080000 ( 0.086071)
#eval 0.360000 0.040000 0.400000 ( 0.405647)
#------------------------------- total: 0.550000sec
# user system total real
#call 0.050000 0.020000 0.070000 ( 0.072041)
#send 0.070000 0.000000 0.070000 ( 0.077674)
#eval 0.370000 0.020000 0.390000 ( 0.399442)
功劳归功于这篇blog post,它详细介绍了这三种方法,并展示了如何检查这些方法是否存在。
发布于 2009-09-10 20:18:57
使用以下命令:
> a = "my_string"
> meth = a.method("size")
> meth.call() # call the size method
=> 9
很简单,对吧?
至于全局变量,我认为Ruby的方法应该是使用methods
方法进行搜索。
https://stackoverflow.com/questions/1407451
复制相似问题