我在the Ruby koans中遇到了这个代理类的解决方案。 :
class Proxy
attr_accessor :messages
def initialize(target_object)
@object = target_object
@messages = []
end
def method_missing(method_name, *args, &block)
@messages << method_name
@object.send(method_name, *args, &block)
end
end
我可以通过传递另一个类作为参数来从此代理类创建一个对象。例如,以下代码将导致 “Do Something”
,而无需键入 thing.method_missing(:do_thing)
:
class Thing
def do_thing
puts "Doing something."
end
end
thing = Proxy.new(Thing.new)
thing.do_thing
为什么即使不调用该方法,method_missing
中的代码也会被执行?
最佳答案
当某个事件发生或某个方法被调用时,有些方法会被隐式调用(即,即使您没有在代码中编写它,也会被调用)。我借用 e-lisp 的术语,将这些方法称为“hooks”。据我所知,Ruby 有以下钩子(Hook):
ruby Hook
at_exit
set_trace_func
initialize
method_missing
singleton_method_added
singleton_method_removed
singleton_method_undefined
respond_to_missing?
extended
included
method_added
method_removed
method_undefined
const_missing
inherited
initialize_copy
initialize_clone
initialize_dup
prepend
append_features
extend_features
prepend_features
而 method_missing
就是其中之一。对于这一特定方法,当 Ruby 找不到已定义的方法时,会自动调用它。或者换句话说,对于任何方法调用,method_missing
是以最低优先级调用的最默认方法。
关于ruby - 方法不调用就执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34258569/