Class: StructuredText::LabeledDelimitedReader

Inherits:
DelimitedReader show all
Defined in:
lib/structuredtext.rb

Overview

Parses field-delimited text with a header row yielding record hashes.

The first row of the file contains field names. This class yields a hash with the field values assigned to their corresponding header names.

> StructuredText::LabeledDelimitedReader.new(<<-EOTEXT
" Fruit,Color,Shape
" apples,red,round
" bananas,yellow,oblong
" EOTEXT
> ).collect
=> [{"Shape"=>"round", "Fruit"=>"apples", "Color"=>"red"}, {"Shape"=>"oblong", "Fruit"=>"bananas", "Color"=>"yellow"}]

If there are fewer fields in a line than there are headers, the remaining ones will be padded with nil. If there are more fields, an RuntimeError will be raised.

Instance Method Summary collapse

Methods inherited from DelimitedReader

#initialize

Constructor Details

This class inherits a constructor from StructuredText::DelimitedReader

Instance Method Details

#eachObject

:yields: Hash of column labels and field values



192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/structuredtext.rb', line 192

def each # :yields: Hash of column labels and field values
  header_row = nil
  super do |record|
    if header_row.nil?
      header_row = record
    else
      if record.length > header_row.length
        raise "More fields than headers:\n#{record.inspect}"
      end
      yield Hash[*header_row.zip(record).flatten]
    end
  end
end