Ruby 3.1 adds Class#subclasses


We often come across situations where we need to inherit the characteristics of one class into another class. Inheritance ensures the “reusability” of codes as while creating a new class, we can derive some of the codes from the existing parent class. This is why Ruby 3.1 has added a new method called Class#subclasses. This returns all classes directly inheriting from the receiver without adding singleton classes.

We can use different implementations from Ruby via gems to calculate subclasses of a particular class. The ActiveSupport::DescendantsTracker is one of the implementations we use in Ruby on Rails. Finally, Ruby has introduced the Class#subclasses native implementation for its latest version of 3.1.

Key terms in Inheritance:

Super class: This is the class whose characteristics are inherited. It is also known as a superclass or base class or parent class.

Sub class: This is the class that is derived from the parent class. It is also known as a subclass or derived class or child class. You can also add its own objects, methods, along with the base class methods and objects, etc.

Note: By default, every class in Ruby has a Super class. Before Ruby 1.9, the Object class was the Super class of all the other Sub classes. Since Ruby 1.9 was introduced, the BasicObject class is the Super class of all the other Sub classes in Ruby. Object class is the Sub class of BasicObject class.

Look at the syntax given below- subclass_name < superclass_name

After Ruby 3.1

class Animal; end

class Dog < Animal; end

class Cat < Animal; end

class GermanShepherd < Dog; end

class SiberianHusky < Dog; end

Animal.subclasses
=> [Dog, Cat]

Dog.subclasses
=> [GermanShepherd, SiberianHusky]

SiberianHusky.subclasses
=> [ ]

To know more about this feature checkout this PR.

Join Our Newsletter