Class: TableFormatterSimple
- Inherits:
-
Object
- Object
- TableFormatterSimple
- Defined in:
- lib/table_formatter_simple.rb
Instance Method Summary collapse
-
#initialize ⇒ TableFormatterSimple
constructor
A new instance of TableFormatterSimple.
- #to_table(data) ⇒ Object
Constructor Details
#initialize ⇒ TableFormatterSimple
Returns a new instance of TableFormatterSimple.
2 3 4 5 |
# File 'lib/table_formatter_simple.rb', line 2 def initialize @space_num = 1 @padstr = ' ' end |
Instance Method Details
#to_table(data) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 60 |
# File 'lib/table_formatter_simple.rb', line 7 def to_table(data) return if data.empty? data2hash = {} length_data = {} formatted_data = '' data.each do |d| d.keys.each do |k| data2hash[k] ||= [] data2hash[k] << d[k] end end data2hash.keys.each do |k| length_data[k] = (data2hash[k].max_by { |f| f.to_s.length }).to_s.length + @space_num * 2 end key_list = data2hash.keys cover = '' key_list.each do |k| cover << '+' cover << '-' * length_data[k] end cover << "+\n" formatted_data << cover index = '' key_list.each do |k| index << '|' index << @padstr * @space_num index << k.to_s.ljust(length_data[k] - @space_num, @padstr) end index << "|\n" formatted_data << index formatted_data << cover rows = '' data.each do |d| row = '' key_list.each do |k| row << '|' row << @padstr * @space_num row << d[k].to_s.ljust(length_data[k] - @space_num, @padstr) end row << "|\n" rows << row end formatted_data << rows formatted_data << cover formatted_data end |