Confusion
Confusion

Reputation: 16841

Test whether a Ruby class is a subclass of another class

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

(N.B. the is_a? test above does not make any sense, as the first comment correctly points out B.new.is_a?(A) would make sense, but is not generally applicable, as not every class has a #initialize method that accepts 0 arguments)

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.

Upvotes: 220

Views: 51605

Answers (2)

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

Just use the < operator

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

or use the <= operator

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

Upvotes: 405

Phrogz
Phrogz

Reputation: 303206

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.

Upvotes: 69

Related Questions