我应该能够Kernel在每个对象上调用方法,并format定义方法Kernel.为什么用第三个例子method_missing调用Kernel?
class A
def method_missing(meth, *args, &block)
if meth == :foo
puts 'ok'
elsif meth == :format
puts 'ok'
end
end
end
a = A.new
a.foo # => ok
a.send(:foo) # => ok
a.format # => ok
a.send(:format) # => too few arguments (ArgumentError)
Run Code Online (Sandbox Code Playgroud)
那是因为Kernel#format是一种私人方法.当你使用它来调用它时send,这意味着你在没有显式接收器的情况下调用它,调用定义的方法,并引发参数错误.当您使用显式接收器调用它时,找不到该方法,因为定义的方法是私有的,因此method_missing被调用.
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |