Re: Writing a parser
- From: Martin Hansen <mail@xxxxxxxxx>
- Date: Fri, 16 Apr 2010 08:13:05 -0500
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/.
.
- Follow-Ups:
- Re: Writing a parser
- From: Robert Klemme
- Re: Writing a parser
- References:
- Writing a parser
- From: Martin Hansen
- Re: Writing a parser
- From: Aldric Giacomoni
- Re: Writing a parser
- From: Martin Hansen
- Re: Writing a parser
- From: Aldric Giacomoni
- Writing a parser
- Prev by Date: Re: Writing a parser
- Next by Date: [ANN] Money 2.3.0
- Previous by thread: Re: Writing a parser
- Next by thread: Re: Writing a parser
- Index(es):
Relevant Pages
|