我发现 Ruby 有一个奇怪的地方。当内核定义相同的方法时,使用 method_missing
/respond_to_missing?
动态处理通过 __send__
发起的方法调用会失败:
class Testerize
def method_missing(method, *args, &block)
if method == :system
puts 'yay'
else
super
end
end
def respond_to_missing?(method, internal)
return true if method == :system
end
end
t = Testerize.new
puts t.respond_to?(:system)
# Prints true
t.system
# Prints 'yay'
t.__send__(:system)
# Exception: wrong number of arguments (ArgumentError)
Kernel.system
以某种方式融入其中。有谁知道这是怎么回事?我本希望将 :system
“消息”发布到 Testerize 实例,点击 method_missing
,瞧。为什么我的 method_missing
在使用 __send__
时没有被调用,而它是直接调用的?
我正在使用 Ruby 1.9.3(如果相关的话)。
最佳答案
with '__send__' or 'send' we can even call private methods of the object.
在您的脚本中执行以下操作:
t.private_methods.grep /system/
您将看到system
方法,同时使用
t.methods.grep /system/
您将看到一个空数组。
__send__
尝试调用继承链中从 Kernel 继承的私有(private)方法,因此不要使用 __send__
,而是使用 Ruby 的 public_send
方法。
关于ruby - 元编程:method_missing 和 __send__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602380/