From: Robert Klemme Date: 2010-04-16T22:35:42+09:00 Subject: Re: Writing a parser 2010/4/16 Martin Hansen : > Ah, of cause I am creating record of class Hash and not class Record. > This does not Err (I wonder if it is sane though): > > class Record < Hash >  SEPERATOR = "\n---\n" Inheriting from core classes is rarely a good idea. Basically your records do not need to be more than Hashes - you just need a proper implementation of fetching records. class RecordSource include Enumerable def self.foreach(file, &b) if block_given? File.open(file) do |io| rs = new(io) rs.each_record(&b) end else Enumerator.new(self, :foreach, file) end end def self.open(file) File.open(file) do |io| yield new(io) end end def initialize(io) @io = io end def each_record curr = {} @io.each_line do |line| case line when /^([^:]+):(.*)$/ curr[$1] = $2 when /^---$/ yield curr unless curr.empty? curr = {} else raise "Illegal format: #{line}" end end yield curr unless curr.empty? self # conventionally end alias :each :each_record end # usage RecordSource.open "myfile" do |rs| rs.each_record do |rec| p rec end end RecordSource.foreach("myfile") do |rec| p rec end p RecordSource.foreach("myfile").to_a Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/