Detecting that a method has not been overridden

Let's say I have the following 2 classes:

class A def a_method end end class B < A end 

Is it possible to discover from inside (an instance) of class B that the a_method method a_method defined only in the superclass, so it is not overridden in B?

Update: Solution

While I marked Chuck’s answer as “accepted,” Paolo Perrota later made me realize that the solution seems to be simpler, and it will probably work with earlier versions of Ruby.

Detection if "a_method" is overridden in B:

 B.instance_methods(false).include?("a_method") 

And for class methods, we use singleton_methods as follows:

 B.singleton_methods(false).include?("a_class_method") 
+6
ruby metaprogramming
source share
4 answers

If you use Ruby 1.8.7 or higher, easy with Method#owner / UnboundMethod#owner .

 class Module def implements_instance_method(method_name) instance_method(method_name).owner == self rescue NameError false end end 
+7
source share
 class A def m1; end def m2; end end class B < A def m1; end def m3; end end obj = B.new methods_in_class = obj.class.instance_methods(false) # => ["m1", "m3"] methods_in_superclass = obj.class.superclass.instance_methods(false) # => ["m2", "m1"] methods_in_superclass - methods_in_class # => ["m2"] 
+2
source share

You can always find the following:

 a = A.new a.methods.include?(:method) 
0
source share

Given object b , which is an instance of b , you can check if b closest superclass with a_method :

 b.class.superclass.instance_methods.include? 'a_method' 

Note that the test contradicts the name of the method, not the symbol or object of the method.

"thus not redefined in B" . Just knowing that a method is defined only in A is difficult because you can define the method in separate instances of A and B ... so I think it will be difficult to verify that a_method is defined only on A because you have to round up all subclasses and substances in the system and test them ...

0
source share

All Articles