Skip to content

Instantly share code, notes, and snippets.

@twe4ked
Created September 15, 2016 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twe4ked/c1a6d0036f2b8e65655089be04b31e7b to your computer and use it in GitHub Desktop.
Save twe4ked/c1a6d0036f2b8e65655089be04b31e7b to your computer and use it in GitHub Desktop.
Ruby ASCII table
# [
# {
# '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