Aligned plain-text terminal table renderer
Crystal
def format_row(cells : Array(String), widths : Array(Int32)) : String
String.build do |io|
cells.each_with_index do |cell, i|
io << " | " if i > 0
io << cell.ljust(widths[i])
end
end
end
def render_table(headers : Array(String), rows : Array(Array(String))) : String
widths = headers.map(&.size)
rows.each do |row|
row.each_with_index { |cell, i| widths[i] = cell.size if cell.size > widths[i] }
end
lines = [format_row(headers, widths), widths.map { |w| "-" * w }.join("-+-")]
rows.each { |row| lines << format_row(row, widths) }
lines.join('\n')
end
puts render_table(["name", "role"], [["Ada", "engineer"], ["Bo", "ops"]])