Getting a pretty list of subclasses

ruby OOP

Mon Feb 08 11:14:35 -0800 2010

Perhaps you are using something like Single Table Inheritance, or are simply for some other reason using a parent class with several subclasses. It can be convenient to be able to quickly get a list of the subclasses of a given parent class.

Ruby does have a subclasses method, but it’s protected, so you need to use something like #send to get to it. But rather than doing that every time, you could just wrap it up in a nifty class method:

class Dog
  class << self
    def kinds
      self.send(:subclasses).map{|n| n.to_s}
    end
  end
end

class Poodle < Dog
end

class Labrador < Dog
end

class Doberman < Dog
end

# irb
>> Dog.kinds
=> ["Poodle", "Labrador", "Doberman"]

Handy.

blog comments powered by Disqus