Skip to content

Instantly share code, notes, and snippets.

@brand-it
Created April 25, 2022 21:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brand-it/789806ceffe33b6fceef2ee4f29b2e61 to your computer and use it in GitHub Desktop.
Save brand-it/789806ceffe33b6fceef2ee4f29b2e61 to your computer and use it in GitHub Desktop.
def format_as_table(header, data)
total_columns = data.first.size
data.insert(0, header) if header
column_widths = total_columns.times.map { |col| data.map { |row| row[col].size }.max }
if header
data.insert(1, Array.new(total_columns, '-').zip(column_widths).map { |a, b| a * b })
end
data.map do |row|
row.zip(column_widths).map do |cell, width|
cell.to_s.ljust(width)
end.join(" | ")
end.join("\n")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment