Console table format in ruby

Viewed 4787

Is there a way to output an array of arrays as a table in ruby? I'm looking for something that is useful from the console, like powershell's format-table command.

An array that would be passed could be something like:

a = [[1.23, 5, :bagels], [3.14, 7, :gravel], [8.33, 11, :saturn]]

And the output could be something like:

-----------------------
| 1.23 |  5 | bagels  |
| 3.14 |  7 | gravel  |
| 8.33 | 11 | saturn  |
-----------------------
3 Answers

I've made a small improvement on the @dart-egregious snippet

class Array
  def to_table(header: true)
    column_sizes = self.reduce([]) do |lengths, row|
      row.each_with_index.map{|iterand, index| [lengths[index] || 0, iterand.to_s.length].max}
    end
    head = '+' + column_sizes.map{|column_size| '-' * (column_size + 2) }.join('+') + '+'
    puts head

    to_print = self.clone
    if (header == true)
      header = to_print.shift
      print_table_data_row(column_sizes, header)
      puts head
    end
    to_print.each{ |row| print_table_data_row(column_sizes, row) }
    puts head
  end

  private
  def print_table_data_row(column_sizes, row)
    row = row.fill(nil, row.size..(column_sizes.size - 1))
    row = row.each_with_index.map{|v, i| v = v.to_s + ' ' * (column_sizes[i] - v.to_s.length)}
    puts '| ' + row.join(' | ') + ' |'
  end
end

Using:

data = [
  ['column 1', 'column 2', 'ciolumn 3'],
  ['row 1 col 2', 'row 1 col 2', 'row 1 col 3'],
  ['row 1 col 2', 'row 1 col 2', 'row 1 col 3']
]

data.to_table
+-------------+-------------+-------------+
| column 1    | column 2    | ciolumn 3   |
+-------------+-------------+-------------+
| row 1 col 2 | row 1 col 2 | row 1 col 3 |
| row 1 col 2 | row 1 col 2 | row 1 col 3 |
+-------------+-------------+-------------+


data.to_table(header: false)
+-------------+-------------+-------------+
| column 1    | column 2    | ciolumn 3   |
| row 1 col 2 | row 1 col 2 | row 1 col 3 |
| row 1 col 2 | row 1 col 2 | row 1 col 3 |
+-------------+-------------+-------------+
Related