From: Robert Klemme Date: 2005-10-24T20:32:01+09:00 Subject: Re: How to find all the subclasses of a class? Horacio Sanson wrote: > I want to be able to list and instatiate all subclasses of a class to > create a Factory type pattern, I want to be able to do something like > > > subclasses = Array.new > > ## Magic code that puts all subclasses of a class in > ## the subclasses array > subclasses = get_subclasses( .... ) > > subclasses.each { |subclass| > return subclass.new if condition == true > end > > > sorry I am very new to Ruby and have no idea on how to do this. > any help is appreciated. There are two possible approaches: 1. Find them when you need them via ObjectSpace: >> cl = Enumerable => Enumerable >> subclasses = [] => [] >> ObjectSpace.each_object(Module) {|m| subclasses << m if m.ancestors.include? cl} => 371 >> subclasses => [Struct::Tms, Dir, File, IO, Range, Struct, Hash, Array, String, Enumerable] 2. Record them when they are created. This is typically done by a variant that uses Class#inherited. >> class Foo >> def self.inherited(cl) >> p cl >> end >> end => nil >> class Bar < Foo >> end Bar => nil Kind regards robert