|
| 1 | +# Print Data To Formatted Table |
| 2 | + |
| 3 | +Often when I'm doing some debugging or reporting from the Ruby/Rails console, I |
| 4 | +end up with a chunk of data that I'd like to share. Usually I'd like something |
| 5 | +that I can copy into the text area of Slack or a project management tool. |
| 6 | +Copying and pasting a pretty-printed hash isn't bad, but a nicely formatted |
| 7 | +table would be even better. |
| 8 | + |
| 9 | +Here is a small method I can copy and paste into the console: |
| 10 | + |
| 11 | +```ruby |
| 12 | +def print_to_table(headings, data) |
| 13 | + # Calculate column widths |
| 14 | + column_widths = headings.each_with_index.map do |heading, index| |
| 15 | + [heading.size, *data.map { |row| row[index].to_s.size }].max |
| 16 | + end |
| 17 | + |
| 18 | + # Method to format a row |
| 19 | + def format_row(row, widths) |
| 20 | + row.each_with_index.map { |item, index| item.to_s.ljust(widths[index]) }.join(" | ") |
| 21 | + end |
| 22 | + |
| 23 | + # Print headings |
| 24 | + puts format_row(headings, column_widths) |
| 25 | + puts "-" * column_widths.sum + "-" * (column_widths.size * 3 - 3) |
| 26 | + |
| 27 | + # Print data |
| 28 | + data.each do |row| |
| 29 | + puts format_row(row, column_widths) |
| 30 | + end |
| 31 | +end |
| 32 | +``` |
| 33 | + |
| 34 | +And then I can run it like so to get formatted table that can be copy-pasted |
| 35 | +elsewhere: |
| 36 | + |
| 37 | +```ruby |
| 38 | +> headings = [:id, :name, :role] |
| 39 | +=> [:id, :name, :role] |
| 40 | +> data = [ |
| 41 | + [123, 'Bob', 'Burger flipper'], |
| 42 | + [456, 'Linda', 'Server'], |
| 43 | + [789, 'Gene', 'Ketchup Refiller'] |
| 44 | + ] |
| 45 | +=> [[123, "Bob", "Burger flipper"], [456, "Linda", "Server"], [789, "Gene", "Ketchup Refiller"]] |
| 46 | +> print_to_table(headings, data) |
| 47 | +# id | name | role |
| 48 | +# ------------------------------ |
| 49 | +# 123 | Bob | Burger flipper |
| 50 | +# 456 | Linda | Server |
| 51 | +# 789 | Gene | Ketchup Refiller |
| 52 | +``` |
0 commit comments