On Tue, Aug 08, 2006 at 06:19:12PM +0900, Kilivor Kante wrote:
> First sorry I am a beginner ;-( What I want to do is: automatically 
> instantiate subclasses of a given class, say, A.
> 
>   class A
>   end
> 
>   class A1 < A
>   end
> 
>   class A2 <A
>   end
> 
> So I want to know the names of A subclasses: A1 and A2. Then instantiate 
> via reflection. Is it possible?

class A
  class << self; attr_reader :subclasses end
  def self.inherited(x); (@subclasses ||= []) << x end
end

class A1 < A; end
class A2 < A; end

A.subclasses                  # => [A1, A2]
A.subclasses.map{|x| x.new}   # => [#<A1:0xa7d73064>, #<A2:0xa7d73050>]

class A1b < A1; end
A1.subclasses                 # => [A1b]


You can use @@subclasses if you want A.subclasses to include A1b:


class A
  @@subclasses = []
  def self.subclasses; @@subclasses end
  def self.inherited(x); @@subclasses << x end
end

class A1 < A; end
class A2 < A; end

A.subclasses                  # => [A1, A2]
A.subclasses.map{|x| x.new}   # => [#<A1:0xa7d3c03c>, #<A2:0xa7d3c028>]

class A1b < A1; end
A.subclasses                 # => [A1, A2, A1b]

-- 
Mauricio Fernandez  -   http://eigenclass.org   -  singular Ruby