module Tablelize

Constants

ALIGN_NUMBER
ALIGN_STRING
HEADER_LINE
SEPARATOR
VERSION

Public Class Methods

table(rows) click to toggle source
# File lib/tablelize.rb, line 9
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