Test whether a Ruby class is a subclass of another class

RubyInheritanceSubclassSuperclass

Ruby Problem Overview


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
=> true

A 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
end

but I would expect this to exist already.

Ruby Solutions


Solution 1 - Ruby

Just use the < operator

B < A # => true
A < A # => false

or use the <= operator

B <= A # => true
A <= A # => true

Solution 2 - Ruby

Also available:

B.ancestors.include? A

This 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
#=> true

Whether or not this is desirable depends on your use case.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionConfusionView Question on Stackoverflow
Solution 1 - RubyMarcel JackwerthView Answer on Stackoverflow
Solution 2 - RubyPhrogzView Answer on Stackoverflow