Top Level Namespace

Defined Under Namespace

Classes: Array, String

Instance Method Summary collapse

Instance Method Details

#tabulate(labels, data, opts = { }) ⇒ Object

tabulate arrays, it accepts the following arguments

  • :label: table headings, an array

  • :data: table data. Each elements stands for one *or more* rows. For example, [[1, 2] , [3, [4, 5]], [nil, 6]] will be processed as 4 lines

    +1      2+
    +3      4+
    +3      5+
    +       6+
    
  • :opts: optional arguments, default to :indent => 0, :style => ‘fancy’

return a String



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/tabulate.rb', line 75

def tabulate(labels, data, opts = { } )
    raise 'Label and data do not have equal columns!' unless labels.size == data.transpose.size

    opts = { :indent => 0, :style => 'fancy'}.merge opts
    indent = opts[:indent]
    style = opts[:style]
    raise "Invalid table style!"    unless  $table_template.keys.include? style

    style = $table_template[style]

    data = data.inject([]){|rs, r| rs += r.to_rows }
    data = data.unshift(labels).transpose
    padding = style[:padding] 
    data = data.collect {|c| 
        c.collect {|e|  ' ' * padding + e.to_s + ' ' * padding } 
    }
    widths = data.collect {|c| c.collect {|a| a.width}.max } 
    newdata = []
    data.each_with_index {|c,i|
        newdata << c.collect { |e| e + ' '*(widths[i] - e.width) }
    }
    data = newdata
    data = data.transpose
    data = [ style[:hlframe] + data[0].join(style[:fs]) + style[:hrframe] ] + \
        data[1..-1].collect {|l| style[:lframe] + l.join(style[:fs]) + style[:rframe] }
    lines = []

    #add top frame
    if !style[:tframe].to_s.empty?
        lines << style[:cross] + widths.collect{|n| style[:tframe] *n }.join(style[:cross]) + style[:cross]
    end

    #add title 
    lines << data[0]

    #add title ruler
    if !style[:hs].to_s.empty? and !style[:lframe].to_s.empty?
        lines << style[:cross] + widths.collect{|n| style[:hs] *n }.join(style[:cross]) + style[:cross]
    elsif !style[:hs].to_s.empty?
        lines << widths.collect{|n| style[:hs] *n }.join(style[:cross])
    end

    #add data
    data[1..-2].each{ |line|
        lines << line
        if !style[:rs].to_s.empty?
            lines << style[:cross] + widths.collect{|n| style[:rs] *n }.join(style[:cross]) + style[:cross]
        end
    }

    #add last record and bottom frame
    lines << data[-1]
    if !style[:bframe].to_s.empty?
        lines << style[:cross] + widths.collect{|n| style[:bframe] *n }.join(style[:cross]) + style[:cross]
    end

    #add indent
    lines.collect {|l| ' '*indent + l}.join("\n")
end