I would like to test whether a class inherits from another class, but there doesn't seem to exist a method for that.
class A
end
class B < A
end
B.is_a? A
=> false
B.superclass == A
=> trueA trivial implementation of what I want would be:
class Class def is_subclass_of?(clazz) return true if superclass == clazz return false if self == Object superclass.is_subclass_of?(clazz) end
endbut I would expect this to exist already.
42 Answers
Just use the < operator
B < A # => true
A < A # => falseor use the <= operator
B <= A # => true
A <= A # => true 9 Also available:
B.ancestors.include? AThis differs slightly from the (shorter) answer of B < A because B is included in B.ancestors:
B.ancestors
#=> [B, A, Object, Kernel, BasicObject]
B < B
#=> false
B.ancestors.include? B
#=> trueWhether or not this is desirable depends on your use case.
10