From: Sean O'Halpin Date: 2005-10-24T20:40:06+09:00 Subject: Re: How to find all the subclasses of a class? On 10/24/05, 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. > > > Horacio Something like this should get you started (though don't expect it to be efficient - it basically queries every object in the system to find the subclasses): class A end class B < A end class C < B end class Class def subclasses class_hash = {} ObjectSpace.each_object do |obj| if Class == obj.class if obj.ancestors.include? self class_hash[obj] = true end end end class_hash.keys end end p A.subclasses #=> [C, B, A] Regards, Sean