Method: Aggregate#to_s

Defined in:
lib/aggregate.rb

#to_s(columns = nil) ⇒ Object

Generate a pretty-printed ASCII representation of the histogram



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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/aggregate.rb', line 107

def to_s(columns=nil)

  #default to an 80 column terminal, don't support < 80 for now
  if nil == columns
    columns = 80
  else
    raise ArgumentError if columns < 80
  end

  #Find the largest bucket and create an array of the rows we intend to print
  disp_buckets = Array.new
  max_count = 0
  total = 0
  @buckets.each_with_index do |count, idx|
    next if 0 == count
    max_count = [max_count, count].max
    disp_buckets << [idx, to_bucket(idx), count]
    total += count
  end

  #XXX: Better to print just header --> footer
  return "Empty histogram" if 0 == disp_buckets.length

  #Figure out how wide the value and count columns need to be based on their
  #largest respective numbers
  value_str = "value"
  count_str = "count"
  total_str = "Total"
  value_width = [disp_buckets.last[1].to_s.length, value_str.length].max
  value_width = [value_width, total_str.length].max
  count_width = [total.to_s.length, count_str.length].max
  max_bar_width  = columns - (value_width + " |".length + "| ".length + count_width)

  #Determine the value of a '@'
  weight = [max_count.to_f/max_bar_width.to_f, 1.0].max

  #format the header
  histogram = sprintf("%#{value_width}s |", value_str)
  max_bar_width.times { histogram << "-"}
  histogram << sprintf("| %#{count_width}s\n", count_str)

  # We denote empty buckets with a '~'
  def skip_row(value_width)
    sprintf("%#{value_width}s ~\n", " ")
  end

  #Loop through each bucket to be displayed and output the correct number
  prev_index = disp_buckets[0][0] - 1

  disp_buckets.each do |x|
    #Denote skipped empty buckets with a ~
    histogram << skip_row(value_width) unless prev_index == x[0] - 1
    prev_index = x[0]

    #Add the value
    row = sprintf("%#{value_width}d |", x[1])

    #Add the bar
    bar_size = (x[2]/weight).to_i
    bar_size.times { row += "@"}
    (max_bar_width - bar_size).times { row += " " }

    #Add the count
    row << sprintf("| %#{count_width}d\n", x[2])

    #Append the finished row onto the histogram
    histogram << row
  end

  #End the table
  histogram << skip_row(value_width) if disp_buckets.last[0] != bucket_count-1
  histogram << sprintf("%#{value_width}s", "Total")
  histogram << " |"
  max_bar_width.times {histogram << "-"}
  histogram << "| "
  histogram << sprintf("%#{count_width}d\n", total)
end