是否有可能在Ruby中获得一个对象的方法的引用(我想知道这是否可以在没有特效/ lambda表达式来完成),例如,考虑下面的代码:如何获得对某种方法的参考?
class X
def initialize
@map = {}
setup_map
end
private
def setup_map
# @map["a"] = get reference to a method
# @map["b"] = get reference to b method
# @map["c"] = get referebce to c method
end
public
def call(a)
@map["a"](a) if a > 10
@map["b"](a) if a > 20
@map["c"](a) if a > 30
end
def a(arg)
puts "a was called with #{arg}"
end
def b(arg)
puts "b was called with #{arg}"
end
def c(arg)
puts "c was called with #{arg}"
end
end
是它可能做这样的事情?我想避免procs/lambdas,因为我想通过继承来改变A,B,C的行为。
This Works!但是,没有办法获得实际的方法参考吗? – Geo 2009-01-27 21:03:26
你可以做的最好的是instance.methods,并给出了一个字符串数组。 – Samuel 2009-01-27 21:17:53