ruby – 为什么只有在使用`send`时才会查找Kernel方法?
发布时间:2020-12-17 03:29:08 所属栏目:百科 来源:网络整理
导读:我应该能够在每个对象上调用Kernel方法,并且在Kernel上定义方法格式.为什么在第三个例子的内核上调用method_missing? class A def method_missing(meth,*args,block) if meth == :foo puts 'ok' elsif meth == :format puts 'ok' end endenda = A.newa.foo
我应该能够在每个对象上调用Kernel方法,并且在Kernel上定义方法格式.为什么在第三个例子的内核上调用method_missing?
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) 解决方法
这是因为Kernel#format是一种私有方法.当您使用send调用它时,这意味着您在没有显式接收器的情况下调用它,将调用已定义的方法,并引发参数错误.当您使用显式接收器调用它时,找不到该方法,因为定义的方法是私有的,因此调用method_missing.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |