Skip to content

Instantly share code, notes, and snippets.

@jmontross
Forked from heftig/test.rb
Created November 30, 2011 19:18
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 jmontross/1410385 to your computer and use it in GitHub Desktop.
Save jmontross/1410385 to your computer and use it in GitHub Desktop.
def printgrid(table)
strings = table.map do |row|
row.map { |cell| cell.to_s }
end
column_widths = []
strings.each do |row|
row.each_with_index do |cell,i|
column_widths[i] = [column_widths[i] || 1, cell.length + 2].max
end
end
row_separator = "+" + column_widths.map { |width| "-" * width }.join("+") + "+"
puts row_separator
strings.each do |row|
justified_row = row.enum_for(:map).with_index do |cell,i|
" " + cell.ljust(column_widths[i] - 1)
end
puts "|" + justified_row.join("|") + "|"
puts row_separator
end
end
table = [[1,2,3],[4,5,6],[7,8,9],[100,200,300]]
printgrid(table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment