Re: Writing a parser
- From: Robert Klemme <shortcutter@xxxxxxxxxxxxxx>
- Date: Fri, 16 Apr 2010 08:35:42 -0500
2010/4/16 Martin Hansen <mail@xxxxxxxxx>:
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/
.
- Follow-Ups:
- Re: Writing a parser
- From: Martin Hansen
- 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
- Re: Writing a parser
- From: Martin Hansen
- Writing a parser
- Prev by Date: Re: DRb: execute method but dont wait for it to finish
- Next by Date: Re: Writing a parser
- Previous by thread: Re: Writing a parser
- Next by thread: Re: Writing a parser
- Index(es):
Relevant Pages
|