Created
September 15, 2016 04:03
-
-
Save twe4ked/c1a6d0036f2b8e65655089be04b31e7b to your computer and use it in GitHub Desktop.
Ruby ASCII table
This file contains 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
# [ | |
# { | |
# 'foo' => 'bar', | |
# 'baz' => 'qux', | |
# }, | |
# { | |
# 'foo' => true, | |
# 'baz' => 1, | |
# }, | |
# ] | |
def print_table(data) | |
# conver to 2D array | |
table = [data.first.keys] + data.map(&:values) | |
widths = [] | |
table.each do |line| | |
c = 0 | |
line.each do |col| | |
col = col.to_s | |
widths[c] = (widths[c] && widths[c] > col.length) ? widths[c] : col.length | |
c += 1 | |
end | |
end | |
# header separator | |
table.insert(1, widths.map { |n| '-' * n }) | |
format = widths.collect { |n| "%-#{n}s"}.join(" | ") | |
table.each_with_index do |line, i| | |
printf "| #{format} |\n", *line | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment