module Tablelize VERSION = "0.1.5" SEPARATOR = ENV.fetch("TABLELIZE_SEPARATOR", " ") HEADER_LINE = ENV.fetch("TABLELIZE_HEADER_LINE", "") ALIGN_STRING = 1 ALIGN_NUMBER = 2 def self.table(rows) aligns = [] widths = [] rows.each_with_index do |row, line| row.each_with_index do |val, index| len = val.to_s.length widths[index] = len if widths[index].nil? || len > widths[index] if line > 0 and aligns[index] != ALIGN_STRING if val.is_a? Numeric aligns[index] = ALIGN_NUMBER else aligns[index] = ALIGN_STRING end end end end format = "" length = 0 widths.each_with_index do |width, index| align = (aligns[index] == ALIGN_NUMBER) ? "" : "-" format = "#{format}%#{align}#{width}s#{SEPARATOR}" length += width end rows.each_with_index do |row, index| printf format.chomp(SEPARATOR) + "\n", *row if index == 0 and HEADER_LINE.length > 0 puts HEADER_LINE * (length -1 + SEPARATOR.size * (rows.size - 1)) end end end end