Search code examples
rubyconsole

Console table format in ruby


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  |
-----------------------

Solution

  • You could try something like this:

    a = [[1.23, 5, :bagels], [3.14, 7, :gravel], [8.33, 11, :saturn]]
    
    bar = '-'*(a[0][0].to_s.length + 4 + a[0][1].to_s.length + 3 + a[0][2].to_s.length + 4) 
    
    puts bar
    a.each do |i|
      i.each.with_index do |j,k|
        if k == 1 && j < 10
          print "|  #{j} "
        else
          print "| #{j} "
        end
      end
      print '|'
      puts
    end
    puts bar
    

    returns:

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

    bar is just an estimate of how long the top and bottom dash-bar will be. In general this code checks each sub-array and prints out its elements with | in the appropriate places. The only tricky bit is the second element of each sub-array. Here we check to see if it is double digit or single digit. The print-format is different for each.

    Bear in mind that this code works specifically for your example and makes a lot of assumptions. Having said that it can be easily modified to taste.