Menu

Published by
Categories: Ruby

I needed a way to get a list of the subclasses that inherit a specific. Unfortunately there is no method like Class.subclasses (there is Class.superclass, though) so I had to look for another way to achieve this. Let’s say, we want to have an array containing all subclasses as a class variable of our superclass Strategy. In order to fill the array we’ll overwrite the inherited class method of Class.

class Strategy
  @subclasses = Array.new
  class << self
    def inherited(klass)
       @subclasses << klass
    end

    def subclasses
      @subclasses.join(', ')
    end
  end
end

Now, every time a class extends Strategy our new inherited method is called and adds the class to our array.

class StrategyA < Strategy; end
class StrategyB < Strategy; end
class StrategyC < Strategy; end

# Let's get the current list of subclasses
puts Strategy.subclasses # will output StrategyA, StrategyB, StrategyC

What happens if a class inherits any of our subclasses? Well, as long as you don’t overwrite the inherited method again it’s also added to the array.