Skip to content

Instantly share code, notes, and snippets.

@devonzuegel
Last active September 15, 2015 22:12
Show Gist options
  • Save devonzuegel/5f05ae74748f358a7668 to your computer and use it in GitHub Desktop.
Save devonzuegel/5f05ae74748f358a7668 to your computer and use it in GitHub Desktop.
Pretty prints a 2D array with or without a header
require 'colorize'
def print_table(table, with_header = true)
# Calculate widths
widths = []
table.each do |line|
line.each_with_index do |col, c|
widths[c] = (widths[c] && widths[c] > col.length) ? widths[c] : col.length
end
end
# Indent the last column left.
last = widths.pop()
format = widths.collect { |n| "%-#{n}s" }.join(" | ".black) + " #{'|'.black} %-#{last}s\n"
table.each_with_index do |line, i|
if i == 0 && with_header
printf(format.black, *line)
else
printf(format, *line)
end
end
end
@devonzuegel
Copy link
Author

Given a two-dimensional array, print_table pretty prints a table that looks a bit like this:

screenshot 2015-09-15 15 07 16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment