#!/usr/bin/env ruby # # http://termos.vemod.net/csv-pretty-printer # require "jcode" class TablePrettyPrinter def initialize(rows) @rows = rows @column_widths = find_column_widths(rows) end def output!(target = STDOUT, padding = " ", separator = " | ") @rows.each do |row| target.puts format_row(row, @column_widths, padding, separator) end end protected def find_column_widths(rows) rows.inject([]) do |widths, row| row.each_with_index do |column, i| width = column.to_s.jsize if width > (widths[i] || 0) widths[i] = width end end next widths end end def format_row(columns, column_widths, padding, separator) columns.zip(column_widths).map { |column, width| column.to_s.ljust(width, padding) }.join(separator) end end