Back to Blog

Ruby 3.1 Class#descendants

on November 23, 2021
This blog is part of our Ruby 3.1 series.

Ruby 3.1 introduces the Class#descendants method which returns all descendants of a class excluding the receiver and singleton classes.

We can see many implementations for calculating all descendant classes 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#descendants 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
4
5=> class Manager < Employee; end
6=> class Developer < Employee; end
7
8=> User.descendants
9=> [Employee, Client, Manager, Developer]
10
11=> Employee.descendants
12=> [Manager, Developer]

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


You might also like

If you liked this blog post, check out similar ones from BigBinary