Method: Tabbit#to_s
- Defined in:
- lib/tabbit.rb
#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 |