2

method_missing出现在 中Object.private_methods,而不出现在 中Object.public_methods

但是,当我打电话时Object.method_missing :stupidmethod,我得到

NoMethodError: undefined method `stupidmethod' for Object:Class

我希望得到

NoMethodError: private method `method_missing' called for Object:Class

因为这就是我尝试调用其他私有方法时得到Object的,例如.Object.chop

作为更多证据,如果我Object.method_missing在没有争论的情况下打电话,我会得到

ArgumentError: no id given

所以看起来我真的是method_missing从它的对象之外调用那个“私有”函数。你能解释一下吗?


编辑:感谢评论中的尤金。 ruby --version告诉我 1.8.7。此外,irb --version是 0.9.5(05/04/13)。很高兴知道这在以后的版本中表现得如我所料。

4

1 回答 1

1

调用的不是私有方法,Object而是模块中的方法Kernel您可以按照类似问题set_trace_func的答案中所述检查调用了哪个方法:

irb(main):001:1> set_trace_func proc { |event, file, line, id, binding, classname|   printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname if id.to_s == 'method_missing' }
=> #<Proc:0x0423d278@(irb):1>
irb(main):002:0> Object.method_missing :test
c-call (irb):4  method_missing   Kernel
c-return (irb):4  method_missing   Kernel
NoMethodError: undefined method `test' for Object:Class
    from (irb):4
    from :0

正如一些评论者在比 1.8.7 更新的 MRI 中指出的那样,这种行为已经改变:method_missing已被删除,Kernel私有实例方法 fromObject被移至BasicObject新的超类。

于 2013-10-11T09:38:52.307 回答