Class: TSV::Row

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/tsv/row.rb

Defined Under Namespace

Classes: InputError, InvalidKey, UnknownKey

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, header) ⇒ Row

Returns a new instance of Row.

Raises:



27
28
29
30
31
32
# File 'lib/tsv/row.rb', line 27

def initialize(data, header)
  @data = data
  @header = header

  raise InputError.new("Row has #{@data.length} columns, but #{@header.length} columns expected") if @data.length != @header.length
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



7
8
9
# File 'lib/tsv/row.rb', line 7

def data
  @data
end

#headerObject (readonly)

Returns the value of attribute header.



7
8
9
# File 'lib/tsv/row.rb', line 7

def header
  @header
end

Instance Method Details

#==(other) ⇒ Object



39
40
41
42
43
# File 'lib/tsv/row.rb', line 39

def ==(other)
  other.is_a?(self.class) and
    header == other.header and
    data == other.data
end

#[](key) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/tsv/row.rb', line 13

def [](key)
  if key.is_a? ::String
    raise UnknownKey unless header.include?(key)

    data[header.index(key)]
  elsif key.is_a? ::Numeric
    raise UnknownKey if data[key].nil?

    data[key]
  else
    raise InvalidKey.new
  end
end

#[]=(key, value) ⇒ Object

Raises:



9
10
11
# File 'lib/tsv/row.rb', line 9

def []=(key, value)
  raise TSV::ReadOnly.new('TSV data is read only. Export data to modify it.')
end

#with_headerObject Also known as: to_h



34
35
36
# File 'lib/tsv/row.rb', line 34

def with_header
  Hash[header.zip(data)]
end