Class: Turnip::Table

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/turnip/table.rb

Defined Under Namespace

Classes: ColumnNotExist, WidthMismatch

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw) ⇒ Table

Returns a new instance of Table.



20
21
22
# File 'lib/turnip/table.rb', line 20

def initialize(raw)
  @raw = raw
end

Instance Attribute Details

#rawObject (readonly) Also known as: to_a

Returns the value of attribute raw.



15
16
17
# File 'lib/turnip/table.rb', line 15

def raw
  @raw
end

Instance Method Details

#eachObject



45
46
47
# File 'lib/turnip/table.rb', line 45

def each
  raw.each { |row| yield(row) }
end

#hashesObject



32
33
34
# File 'lib/turnip/table.rb', line 32

def hashes
  rows.map { |row| Hash[headers.zip(row)] }
end

#headersObject



24
25
26
# File 'lib/turnip/table.rb', line 24

def headers
  raw.first
end

#map_column!(name, strict = true) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/turnip/table.rb', line 49

def map_column!(name, strict = true)
  index = headers.index(name.to_s)
  if index.nil?
    raise ColumnNotExist.new(name) if strict
  else
    rows.each { |row| row[index] = yield(row[index]) }
  end
end

#rowsObject



28
29
30
# File 'lib/turnip/table.rb', line 28

def rows
  raw.drop(1)
end

#rows_hashObject

Raises:



36
37
38
39
# File 'lib/turnip/table.rb', line 36

def rows_hash
  raise WidthMismatch.new(2, width) unless width == 2
  transpose.hashes.first
end

#transposeObject



41
42
43
# File 'lib/turnip/table.rb', line 41

def transpose
  self.class.new(raw.transpose)
end