说,我有以下两个类:
- class A
- def a_method
- end
- end
- class B < A
- end
是否有可能从类B的内部(实例)中检测到方法a_method仅在超类中定义,因此不会在B中被覆盖?
更新:解决方案
虽然我已经将Chuck的答案标记为“已接受”,但后来Paolo Perrota让我意识到解决方案显然可以更简单,并且它可能也适用于早期版本的Ruby.
检测B中是否覆盖了“a_method”:
- B.instance_methods(false).include?("a_method")
对于类方法,我们类似地使用singleton_methods:
- B.singleton_methods(false).include?("a_class_method")
解决方法
如果您使用的是Ruby 1.8.7或更高版本,则可以使用Method#owner / UnboundMethod#owner轻松实现.
- class Module
- def implements_instance_method(method_name)
- instance_method(method_name).owner == self
- rescue NameError
- false
- end
- end