为什么只有在使用`send`时才会查找Kernel方法?

时间:2014-05-22 12:23:39

标签: ruby

我应该能够在每个对象上调用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)

1 个答案:

答案 0 :(得分:7)

这是因为Kernel#format是私有方法。当您使用send调用它时,这意味着您在没有显式接收器的情况下调用它,将调用已定义的方法,并引发参数错误。当您使用显式接收器调用它时,找不到该方法,因为定义的方法是私有的,因此调用method_missing