Module: Conscriptor::Histogram

Included in:
Conscriptor, EventCounter
Defined in:
lib/conscriptor/histogram.rb

Instance Method Summary collapse

Instance Method Details

#histogram(things, indent: '') ⇒ Object

Takes an array of values, groups them by identity and counts them, then produces a string output that can be printed.

928 Foo 55 Bar 5 Baz



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/conscriptor/histogram.rb', line 9

def histogram(things, indent: '')
  occurences = {}
  things.each do |thing|
    occurences[thing] = (occurences[thing] || 0) + 1
  end
  lines = occurences
          .sort_by { |a, b| [b, a.to_s] }
          .reverse
          .map { |thing, count| "#{count}\t #{thing}" }

  "#{indent}#{lines.join("\n#{indent}")}"
end