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/.

.



Relevant Pages

  • Re: comparing objects
    ... let's be clear about the semantics of the various comparison methods: ... The Array#& operator, like its siblings, uses the #hash and #eql? ... def eql? ...
    (comp.lang.ruby)
  • Re: A newbie needs insight into some Ruby proboems...
    ... My first problem is that I have a class and I want to define some operators, like equality. ... def initialize ... What I'm trying to do is automate iterating over my member variables performing a cumulative equality test. ... I have to define something like a "hash" method but I don't know what hash is supposed to return, exactly, for things like Set and Hash to work. ...
    (comp.lang.ruby)
  • Re: Behaviour of Enumerables reject vs. select mixed into Hash
    ... Yes, but making a special case of Hash, as opposed to other ... more harmful to duck-typing than either not returning an array. ... def add_from_e_method ... self << elem ...
    (comp.lang.ruby)
  • Re: update variables based on own value - critique please?
    ... This is not DRY. ... def send_updates! ... # updates values based on blocks passed in a hash ... By the way -- is there any way to have json parse return keys as ...
    (comp.lang.ruby)
  • 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)