Ruby 3.1 adds Class#subclasses

Ashik Salman

By Ashik Salman

on December 27, 2021

This blog is part of our  Ruby 3.1 series.

Ruby 3.1 introduces the Class#subclasses method which returns all classes directly inheriting from the receiver without including singleton classes.

We can see many implementations for calculating all subclasses of a particular class from the Ruby community with different gems. The ActiveSupport::DescendantsTracker is one of such implementations used in Rails framework. Finally, Ruby has added the Class#subclasses native implementation for it's 3.1 version release.

After Ruby 3.1

1=> class User; end
2=> class Employee < User; end
3=> class Client < User; end
5=> class Manager < Employee; end
6=> class Developer < Employee; end
8=> User.subclasses
9=> [Employee, Client]
11=> Employee.subclasses
12=> [Manager, Developer]
14=> Developer.subclasses
15=> []

Here's the relevant pull request and feature discussion for this change.