我们知道,方法Module#refine
是Module
类中的私有实例方法:
% Module.private_instance_methods(false)
[:remove_const, :method_added, :append_features, :method_removed,
:method_undefined, :extend_object, :prepend_features, :using, :refine,
:initialize, :initialize_copy, :initialize_clone, :public, :protected,
:module_function, :private, :included, :extended, :prepended]
这意味着Object
类本身可以使用refine
或Object#send
调用BasicObject#__send__
方法,因为Object.singleton_class.ancestors.include?(Module)
为真。
但执行undefined method
时会出现实际Object.refine
错误:
# ./tmp/mytest.rb
Module.private_instance_methods(false).map do |m|
begin
p [m, Object.singleton_class.instance_method(m)]
rescue StandardError => e
p [m, e.exception]
end
end
输出就是这个。 refine
方法位于中间。
% ruby -v
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-darwin17]
% ruby ./tmp/mytest.rb
[:remove_const, #<UnboundMethod: #<Class:Object>#remove_const>]
[:method_added, #<UnboundMethod: #<Class:Object>#method_added>]
[:append_features, #<NameError: undefined method `append_features' for class `#<Class:Object>'>]
[:method_removed, #<UnboundMethod: #<Class:Object>#method_removed>]
[:method_undefined, #<UnboundMethod: #<Class:Object>#method_undefined>]
[:extend_object, #<NameError: undefined method `extend_object' for class `#<Class:Object>'>]
[:prepend_features, #<NameError: undefined method `prepend_features' for class `#<Class:Object>'>]
[:using, #<UnboundMethod: #<Class:Object>#using>]
[:refine, #<NameError: undefined method `refine' for class `#<Class:Object>'>]
[:initialize, #<UnboundMethod: #<Class:Object>#initialize>]
[:initialize_copy, #<UnboundMethod: #<Class:Object>#initialize_copy>]
[:initialize_clone, #<UnboundMethod: #<Class:Object>#initialize_clone>]
[:public, #<UnboundMethod: #<Class:Object>#public>]
[:protected, #<UnboundMethod: #<Class:Object>#protected>]
[:module_function, #<NameError: undefined method `module_function' for class `#<Class:Object>'>]
[:private, #<UnboundMethod: #<Class:Object>#private>]
[:included, #<UnboundMethod: #<Class:Object>#included>]
[:extended, #<UnboundMethod: #<Class:Object>#extended>]
[:prepended, #<UnboundMethod: #<Class:Object>#prepended>]
在上面的结果中,refine
方法除外,append_features
,prepend_features
,extend_object
和module_function
方法提升NameError
,而其他方法成功查找方法。
看起来好奇,我想知道会发生什么。
答案 0 :(得分:0)
经过检查,operator delete(p)
似乎是:refine
,但我在UnboundMethod
周围发现了这一点。从pry控制台:
pry
您会注意到:
Module.private_instance_methods(:false)
[ 76] refine(arg1) Module (unbound)
NameError
代码示例中出现了{{1}}