Ruby aligned plain-text table renderer
Ruby
def render_table(headers, rows)
raise ArgumentError, 'headers are required' if headers.empty?
data = [headers.map(&:to_s)] + rows.map { |row| headers.each_index.map { |index| row[index].to_s } }
widths = headers.each_index.map do |index|
data.map { |row| row[index].length }.max
end
border = widths.map { |width| '-' * width }.join('-+-')
body = data.map do |row|
row.each_with_index.map { |cell, index| cell.ljust(widths[index]) }.join(' | ')
end
[border, body[0], border, *body[1..], border].join(10.chr)
end