Re: Writing a parser



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/

.



Relevant Pages

  • Re: Trouble using string.tr()
    ... parses a record at a time, building the output ASCII row. ... def Record.report_values; # ebcdic data ... end; # class Record. ... translate process. ...
    (comp.lang.ruby)
  • Re: Writing a parser
    ... of cause I am creating record of class Hash and not class Record. ... This does not Err (I wonder if it is sane though): ... def get_record ...
    (comp.lang.ruby)
  • Re: Dynamically create a class (or class instance) and its attributes?
    ... > class instance that would allow me to access the fields in the MySQL row ... def makeProperty: ... with SQLObject.(Am I repeating myself? ...
    (comp.lang.python)
  • void value expression
    ... I wrote a Ruby script ... def initialize ...
    (comp.lang.ruby)