继承BasicObject后#inspect在IRB中异常,如何实现正常调用?
问题解答
当继承BasicObject后,即便手动实现了#inspect方法,IRB直接输出实例时仍提示(Object doesn't support #inspect),核心原因是:IRB在输出对象前会调用respond_to?(:inspect)检查方法支持情况,但BasicObject未包含Kernel模块,本身没有respond_to?方法,导致IRB误判对象不支持#inspect。
可以通过以下两种方式解决,让IRB正常识别并调用自定义的#inspect:
方案一:包含Kernel模块
让子类包含Kernel模块,继承respond_to?等常用方法:
class Test < BasicObject include Kernel def inspect "foobar" end end
此时在IRB中直接输入实例变量test,会输出:=> foobar。
方案二:手动实现respond_to?方法
仅针对inspect方法实现响应检查,无需引入整个Kernel:
class Test < BasicObject def inspect "foobar" end def respond_to?(method_name, include_private = false) method_name == :inspect || super end end
IRB会通过respond_to?的检查,正确调用自定义的#inspect方法输出结果。
内容的提问来源于stack exchange,提问作者svoop
相关产品推荐
相关产品推荐

