instance method · added in Ruby 3.1
Class#subclasses
() -> ::Array[::Class]
subclasses → array
object.c
View on GitHub ↗
VALUE
rb_class_subclasses(VALUE klass)
{
return class_descendants(klass, true);
}
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
-
3.1
-
Class#subclasses, which returns an array of classes directly inheriting from the receiver, not including singleton classes. [Feature #18273]Exampleclass A; end class B < A; end class C < B; end class D < A; end A.subclasses #=> [D, B] B.subclasses #=> [C] C.subclasses #=> []
-