Last active
September 15, 2015 22:12
-
-
Save devonzuegel/5f05ae74748f358a7668 to your computer and use it in GitHub Desktop.
Pretty prints a 2D array with or without a header
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given a two-dimensional array,
print_table
pretty prints a table that looks a bit like this: