I believe you are looking for this:
class Class
def instance_methods_within(klass)
return self.instance_methods if klass == Object
methods = []
this = self
while this != nil
methods << this.instance_methods(false)
break if this == klass
this = this.superclass
end
return methods.flatten
end
end
class C; def c; end end
class B < C; def b; end end
class D < B; def d; end end
class A < D; def a; end end
A.instance_methods_within(Object) # => (Same as A.instance_methods)
A.instance_methods_within(C) # => [:a, :d, :b, :c]
A.instance_methods_within(B) # => [:a, :d, :b]
A.instance_methods_within(D) # => [:a, :d]
A.instance_methods_within(A) # => [:a] (Same as A.instance_methods(false))
I added the special case for Object
as Object.instance_methods(false)
yields []
, thus the loop traversing upwards would not work well in that case. Updated to define the instance_methods_within
class as an instance method of Class
.