Class: Tabbit
- Inherits:
-
Object
- Object
- Tabbit
- Defined in:
- lib/tabbit.rb
Instance Method Summary collapse
-
#add_row(*items) ⇒ Object
Adds line to @table in form of Array.
-
#initialize(*headers) ⇒ Tabbit
constructor
Table initialized as an Array.
- #size ⇒ Object
-
#to_s ⇒ Object
Changes @table Array into format for printing to console.
Constructor Details
#initialize(*headers) ⇒ Tabbit
Table initialized as an Array
8 9 10 11 |
# File 'lib/tabbit.rb', line 8 def initialize(*headers) @table = [[]] headers.each { |h| @table[0].push h } end |
Instance Method Details
#add_row(*items) ⇒ Object
Adds line to @table in form of Array
14 15 16 17 18 |
# File 'lib/tabbit.rb', line 14 def add_row(*items) line = [] items.each { |i| line.push i } @table.push line end |
#size ⇒ Object
61 62 63 |
# File 'lib/tabbit.rb', line 61 def size @table.length - 1 end |
#to_s ⇒ Object
Changes @table Array into format for printing to console.
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/tabbit.rb', line 21 def to_s @table[0].length.times do |n| self.instance_variable_set "@max_length_#{n}", 0.0 # Finds the longest string in column @table.each do |line| if line[n].to_s.length > self.instance_variable_get("@max_length_#{n}") self.instance_variable_set "@max_length_#{n}", line[n].length.to_f end end end divider '=', @table, new_line: true @table[0].length.times do |n| difference = self.instance_variable_get("@max_length_#{n}") - @table[0][n].to_s.length + 2 cell = '|' + (' ' * 2) + @table[0][n].to_s.bold.red + (' ' * difference) @table[0][n] == @table[0].last ? puts(cell + '|') : print(cell) end divider '=', @table, new_line: true # Write the table body, amount of spaces depends on the maximum length of # that column. @table.length.times do |n| unless n == 0 line = @table[n] line.length.times do |i| item = line[i] difference = self.instance_variable_get("@max_length_#{i}") - item.to_s.length + 2 cell = '|' + (' ' * 2) + item.to_s + (' ' * difference) item == line.last ? puts(cell + '|') : print(cell) end end end divider '=', @table end |