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.
=> class User; end
=> class Employee < User; end
=> class Client < User; end
=> class Manager < Employee; end
=> class Developer < Employee; end
=> User.subclasses
=> [Employee, Client]
=> Employee.subclasses
=> [Manager, Developer]
=> Developer.subclasses
=> []
Here's the relevant pull request and feature discussion for this change.

Written byAshik Salman
Related blogs
- 01Ruby 3.1 adds MatchData#match & MatchData#match_lengthNovember 9, 2021 · Ashik Salman
- 02Ruby 3.1 adds Array#intersect?May 11, 2021 · Ashik Salman
- 03Ruby 3.1 accumulates Enumerable#tally resultsApril 20, 2021 · Ashik Salman
- 04Ruby 3.1 adds Enumerable#compact and Lazy#compactApril 6, 2021 · Ashik Salman