RubyGreenBlue

Finding Descendants of a Class

Posted by keith about 1 year ago

Ruby offers a method for finding all the ancestors of a class (ancestors funnily enough) but, as far as I know, no easy way to get at all the descendants of a class.

I thought it had to be possible, this *is* Ruby after all! But in thinking about it a little more, I figured it could well be a tricky thing to do and probably require some hook in the Ruby language for it all to be even possible.

Luckily I found this beauty: ObjectSpace. With ObjectSpace you can eacherate over every object in the Ruby object space. What else?

So it tuns out that finding all the descendants of a particular class is not such a big deal after all. Just eacherate over ObjectSpace and do a little recursion:

class Object

  def self.show_descendants(klass = nil, indent_level = 1)
    unless klass
      klass = self
      puts ' - ' * (indent_level) + klass.to_s
    end
    ObjectSpace.each_object do |obj|
      if obj.class == Class and obj.superclass == klass
        puts ' - ' * (indent_level + 1) + obj.to_s
        show_descendants(obj, indent_level + 1)
      end
    end
  end

  def show_descendants(klass, indent_level = 1)
    klass.show_descendants(nil, indent_level)
  end

end


# you can pass the class as an argument
show_descendants(ScriptError)

# or you can send the method to the class
Numeric.show_descendants

This code could be modified a little to return a list of descendants, each containing their own list of descendants rather than putsing it all to the screen.