From: Martin Hansen Date: 2010-04-16T22:13:05+09:00 Subject: Re: Writing a parser 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" include Enumerable def initialize(path=nil) @path = path @ios = File.open(@path, 'r') if @path end # Reads the next 'record' from the I/O stream. The records are separated by # lines of "---" and each record consists of a varying number of lines with # a key/value pair separated by ": ". The record is returned as a hash. def get_record block = @ios.gets(SEPERATOR).chomp!(SEPERATOR) record = Record.new block.each_line do |line| fields = line.split(": ") raise ArgumentError, "Bad record line: #{line}" if fields.length != 2 record.add(fields[0],fields[1]) end record end # Add a key value pair to this record. def add(key, value) raise ArgumentError, "Bad key contains ': ' or '\n' ->#{key}" if key.match(": |\n") raise ArgumentError, "Bad value contains ': ' or '\n' ->#{value}" if value.match(": |\n") self[key] = value end # Return the content of this record as a string. def to_s return nil if empty? self.map { | key, val | "#{ key }: #{ val }" }.join( "\n" ) + SEPERATOR end end -- Posted via http://www.ruby-forum.com/.