Ruby 3.1 adds Class#subclasses

Ashik Salman

Ashik Salman

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

=> 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.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.