<- Back

Look up all the descendants of a class in Ruby

Exploring Ruby's ObjectSpace module and how to find all child classes that inherit from a base class.

During my free time, I often try to read some OSS code. This time I started taking a look at the faker bot codebase, and while reading I found this bit of interesting code 👇🏻

def self.descendants
  @descendants ||= ObjectSpace.each_object(Class).select do |klass|
    klass < self
  end
end

This particular block of code will list out all the child classes which inherit from the base class.

example:

class Parent
  def self.descendants
    ObjectSpace.each_object(Class).select { |klass| klass < self }
  end
end

class Child < Parent
end

class GrandChild < Child
end

puts Parent.descendants # [Grandchild, Child]
puts Child.descendants # GrandChild

By now you must be like, what the hell is ObjectSpace?

ObjectSpace module defines a handful of low-level methods that can be occasionally useful for debugging or metaprogramming.

The most notable of the methods defined by the ObjectSpace module is the each_object, an iterator that can yield every object (or every instance of a specified class) that the interpreter knows about.


Read more about ObjectSpace: