From: 7stud -- Date: 2011-04-19T05:22:05+09:00 Subject: Re: Making a simple parser 7stud -- wrote in post #993588: > > Note that when inherited() is called, the methods of the subclass are > not defined yet, so if you create objects of the subclass inside > inherited(), the initialize() method in the parent is called. > And you can get around that problem by letting InputFormat#parse create the objects: class InputFormat @children = [] def self.children @children end def initialize(input) @input = input end def parse InputFormat.children.each { |child| instance = child.new instance.parse(@input) if instance.supported? } end def self.inherited(sub_class) @children << sub_class end end class InputFormatA < InputFormat def initialize puts "Initializing instance of #{self.class}" end def supported? true end def parse(str) puts "InputFormatA is parsing #{str}" end end class InputFormatB < InputFormat def initialize puts "Initializing instance of #{self.class}" end def supported? true end def parse(str) puts "InputFormatB is parsing #{str}" end end input = InputFormat.new('hello world') input.parse --output:-- Initializing instance of InputFormatA InputFormatA is parsing hello world Initializing instance of InputFormatB InputFormatB is parsing hello world -- Posted via http://www.ruby-forum.com/.