Skip to content
instance method · added in Ruby 3.1

Class#subclasses

() -> ::Array[::Class]
subclasses → array

Returns an array of classes where the receiver is the direct superclass of the class, excluding singleton classes. The order of the returned array is not defined.

Example
class A; end
class B < A; end
class C < B; end
class D < A; end

A.subclasses        #=> [D, B]
B.subclasses        #=> [C]
C.subclasses        #=> []

Anonymous subclasses (not associated with a constant) are returned, too:

Example
c = Class.new(A)
A.subclasses        # => [#<Class:0x00007f003c77bd78>, D, B]

Note that the parent does not hold references to subclasses and doesn’t prevent them from being garbage collected. This means that the subclass might disappear when all references to it are dropped:

Example
# drop the reference to subclass, it can be garbage-collected now
c = nil

A.subclasses
# It can be
#  => [#<Class:0x00007f003c77bd78>, D, B]
# ...or just
#  => [D, B]
# ...depending on whether garbage collector was run

Ruby version changes

  1. 3.1
    • Class#subclasses, which returns an array of classes directly inheriting from the receiver, not including singleton classes. [Feature #18273]

      Example
      class A; end
      class B < A; end
      class C < B; end
      class D < A; end
      A.subclasses    #=> [D, B]
      B.subclasses    #=> [C]
      C.subclasses    #=> []
      
See also #new #superclass #inherited also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1