我正在处理旧版的 Ruby 代码,但是我无法理解这段代码的运作。这个函数是:
def determine_caller(host)
if host["name"] =~ /special/
method(:call_special)
else
method(:call_normal)
end
end
后来这种方法被称为:
caller = determine_caller(host_name)
程序最终使用caller作为变量,在另一个类中运行一个方法。程序后面的
call_special
和call_normal
是方法。我认为这是定义一个方法以发送到另一个方法,以便在需要时调用该方法(无论是call_special
还是call_normal
),但我不明白determin_caller
如何返回任何内容。我认为method
关键字会调用方法本身,但至少根据我理解的程序来看,这不可能是正确的。
def a(msg) puts "#{msg}, Bob" end
,def say() method(:a) end
和m = say #=> #<Method: Object#a>
,那么m.call("Hi") #=> Hi, Bob
。 - Cary Swoveland