Class: Stat::Table
- Inherits:
-
Object
- Object
- Stat::Table
- Defined in:
- lib/stat/table.rb
Overview
Table represents a table data file (actual file format may differ)
Instance Attribute Summary collapse
-
#records ⇒ Object
readonly
Returns the value of attribute records.
Instance Method Summary collapse
-
#fields ⇒ Object
Use it to define fields in subclasses.
-
#initialize ⇒ Table
constructor
A new instance of Table.
- #length ⇒ Object
-
#read(filename, constructor, n = nil) ⇒ Object
Reads in data file.
-
#recode ⇒ Object
Child classes can override this to recode values.
-
#to_csv ⇒ Object
Turn Table into CSV format.
Constructor Details
#initialize ⇒ Table
Returns a new instance of Table.
9 10 11 |
# File 'lib/stat/table.rb', line 9 def initialize @records = [] end |
Instance Attribute Details
#records ⇒ Object (readonly)
Returns the value of attribute records.
7 8 9 |
# File 'lib/stat/table.rb', line 7 def records @records end |
Instance Method Details
#fields ⇒ Object
Use it to define fields in subclasses
18 19 20 |
# File 'lib/stat/table.rb', line 18 def fields [] end |
#length ⇒ Object
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 |
#recode ⇒ Object
Child classes can override this to recode values
35 36 37 |
# File 'lib/stat/table.rb', line 35 def recode self end |
#to_csv ⇒ Object
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 |