Class: Squib::DataFrame

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/squib/import/data_frame.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}, def_columns = true) ⇒ DataFrame

Returns a new instance of DataFrame.



10
11
12
13
# File 'lib/squib/import/data_frame.rb', line 10

def initialize(hash = {}, def_columns = true)
  @hash = hash
  columns.each { |col| def_column(col) } if def_columns
end

Instance Method Details

#[](i) ⇒ Object



19
20
21
# File 'lib/squib/import/data_frame.rb', line 19

def [](i)
  @hash[i]
end

#[]=(col, v) ⇒ Object



23
24
25
26
27
# File 'lib/squib/import/data_frame.rb', line 23

def []=(col, v)
  @hash[col] = v
  def_column(col)
  return v
end

#col?(col) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/squib/import/data_frame.rb', line 37

def col?(col)
  @hash.key? col
end

#columnsObject



29
30
31
# File 'lib/squib/import/data_frame.rb', line 29

def columns
  @hash.keys
end

#each(&block) ⇒ Object



15
16
17
# File 'lib/squib/import/data_frame.rb', line 15

def each(&block)
  @hash.each(&block)
end

#ncolumnsObject



33
34
35
# File 'lib/squib/import/data_frame.rb', line 33

def ncolumns
  @hash.keys.size
end

#nrowsObject



45
46
47
# File 'lib/squib/import/data_frame.rb', line 45

def nrows
  @hash.inject(0) { |max, (_n, col)| col.size > max ? col.size : max }
end

#row(i) ⇒ Object



41
42
43
# File 'lib/squib/import/data_frame.rb', line 41

def row(i)
  @hash.inject(Hash.new) { |ret, (name, arr)| ret[name] = arr[i]; ret }
end

#to_hObject



57
58
59
# File 'lib/squib/import/data_frame.rb', line 57

def to_h
  @hash
end

#to_jsonObject



49
50
51
# File 'lib/squib/import/data_frame.rb', line 49

def to_json
  @hash.to_json
end

#to_pretty_jsonObject



53
54
55
# File 'lib/squib/import/data_frame.rb', line 53

def to_pretty_json
  JSON.pretty_generate(@hash)
end

#to_pretty_textObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/squib/import/data_frame.rb', line 61

def to_pretty_text
  max_col = columns.inject(0) { |max, c | c.length > max ? c.length : max }
  top    = "#{'-' * 36}╮\n"
  bottom = "#{'-' * 36}╯\n"
  str =  ''
  0.upto(nrows - 1) do | i |
    str += (' ' * max_col) + top
    row(i).each do |col, data|
      str += "#{col.rjust(max_col)} #{wrap_n_pad(data, max_col)}"
    end
    str += (' ' * max_col) + bottom
  end
  return str
end