Sha256: bf8c11da2fc4985c6ce0934d8885fe1c2b1f96c5d9e08db1484fa156b68e1f59

Contents?: true

Size: 1.35 KB

Versions: 3

Compression:

Stored size: 1.35 KB

Contents

module Tailstrom
  class Table
    def initialize(schema)
      @schema = schema
      @out = $stdout
    end

    def print_row(*cols)
      cols.each_with_index do |col, i|
        col_schema = @schema[i]
        num_str = col ? num_with_delim(col) : '-'
        print ' ' if i > 0
        printf "%#{col_schema[:width]}s", num_str
      end
      @out.puts
    end

    def print_header
      border = head = ''
      @schema.each_with_index do |col, i|
        if i > 0
          border += '-'
          head   += ' '
          #border += '+'
          #head   += '|'
        end
        border += '-' * col[:width]
        head   += "%#{col[:width]}s" % col[:name]
      end
      @out.puts border, head, border
    end

    private
      def num_with_delim(num)
        head, tail = num.to_s.split('.')
        head.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
        if tail
          "#{head}.#{tail[0..2]}"
        else
          head
        end
      end
  end
end

if $0 == __FILE__
  nums = [
459938.0869565217,
588316.4761904762,
459265.652173913,
473729.63636363635,
625076.2857142857,
461625.76,
412747.04761904763,
367196.3,
0.125,
9.50,
10.1,
100,
100
  ]

  schema = [
    { :name => 'min', :width => 15 },
    { :name => 'max', :width => 15 },
  ]

  table = Tailstrom::Table.new schema
  table.print_header
  nums.each do |num|
    table.print_row num, num
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tailstrom-0.0.3 lib/tailstrom/table.rb
tailstrom-0.0.2 lib/tailstrom/table.rb
tailstrom-0.0.1 lib/tailstrom/table.rb