Class: Stat::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/stat/table.rb

Overview

Table represents a table data file (actual file format may differ)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTable

Returns a new instance of Table.



9
10
11
# File 'lib/stat/table.rb', line 9

def initialize
  @records = []
end

Instance Attribute Details

#recordsObject (readonly)

Returns the value of attribute records.



7
8
9
# File 'lib/stat/table.rb', line 7

def records
  @records
end

Instance Method Details

#fieldsObject

Use it to define fields in subclasses



18
19
20
# File 'lib/stat/table.rb', line 18

def fields
  []
end

#lengthObject



13
14
15
# File 'lib/stat/table.rb', line 13

def length
  @records.length
end

#read(filename, constructor, n = nil) ⇒ Object

Reads in data file



23
24
25
26
27
28
29
30
31
32
# File 'lib/stat/table.rb', line 23

def read filename, constructor, n=nil
  file = Pathname.new(filename)
  file.open('r') do |file|
    file.readlines.each_with_index do |line, i|
      break if i == n
      @records << constructor.new(fields, line)
    end
  end
  self
end

#recodeObject

Child classes can override this to recode values



35
36
37
# File 'lib/stat/table.rb', line 35

def recode
  self
end

#to_csvObject

Turn Table into CSV format



40
41
42
43
44
45
# File 'lib/stat/table.rb', line 40

def to_csv
  fields.map(&:first).join(',') + "\n" +
      records.map do |rec|
        fields.map { |(name, _, _, _)| rec.send(name) || '' }.join(',')
      end.join("\n")
end