我怎样才能得到一个方法的参考? [英] How can I get a reference to a method?
本文介绍了我怎样才能得到一个方法的参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能在Ruby中获取对象方法的引用(我想知道是否可以在不使用procs / lambdas的情况下完成此操作),例如,请考虑以下代码:
Is it possible in Ruby to get a reference to methods of an object ( I would like to know if this can be done without procs/lambdas ) , for example , consider the following code :
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的行为。
Is it possible to do such thing ? I would like to avoid procs/lambdas because I want to be able to change the behaviour of A,B,C by subclassing .
推荐答案
< Object#method :
---------------------------------------------------------- Object#method
obj.method(sym) => method
------------------------------------------------------------------------
Looks up the named method as a receiver in obj, returning a Method
object (or raising NameError). The Method object acts as a closure
in obj's object instance, so instance variables and the value of
self remain available.
class Demo
def initialize(n)
@iv = n
end
def hello()
"Hello, @iv = #{@iv}"
end
end
k = Demo.new(99)
m = k.method(:hello)
m.call #=> "Hello, @iv = 99"
l = Demo.new('Fred')
m = l.method("hello")
m.call #=> "Hello, @iv = Fred"
现在您的代码变为:
Now your code becomes:
private
def setup_map
@map = {
'a' => method(:a),
'b' => method(:b),
'c' => method(:c)
}
# or, more succinctly
# @map = Hash.new { |_map,name| _map[name] = method(name.to_sym) }
end
public
def call(arg)
@map["a"][arg] if arg > 10
@map["b"][arg] if arg > 20
@map["c"][arg] if arg > 30
end
这篇关于我怎样才能得到一个方法的参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文