Class: CodeHistogram
- Inherits:
-
Object
- Object
- CodeHistogram
- Defined in:
- lib/zombie_killer/code_histogram.rb
Overview
Keep track of the count of occurences of things (in code)
Instance Attribute Summary collapse
-
#counts ⇒ Object
readonly
Returns the value of attribute counts.
Class Method Summary collapse
Instance Method Summary collapse
- #increment(key, value = 1) ⇒ Object
-
#initialize ⇒ CodeHistogram
constructor
A new instance of CodeHistogram.
- #merge!(other) ⇒ Object
- #print_by_frequency(io) ⇒ Object
Constructor Details
#initialize ⇒ CodeHistogram
Returns a new instance of CodeHistogram.
7 8 9 10 11 |
# File 'lib/zombie_killer/code_histogram.rb', line 7 def initialize @counts = Hash.new do |hash, key| hash[key] = 0 end end |
Instance Attribute Details
#counts ⇒ Object (readonly)
Returns the value of attribute counts.
5 6 7 |
# File 'lib/zombie_killer/code_histogram.rb', line 5 def counts @counts end |
Class Method Details
.parse_by_frequency(lines) ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/zombie_killer/code_histogram.rb', line 27 def self.parse_by_frequency(lines) histogram = CodeHistogram.new lines.each do |line| /^\s*(\d*)\s*(.*)/.match(line.chomp) do |m| histogram.increment(m[2], m[1].to_i) end end histogram end |
Instance Method Details
#increment(key, value = 1) ⇒ Object
13 14 15 |
# File 'lib/zombie_killer/code_histogram.rb', line 13 def increment(key, value = 1) @counts[key] += value end |
#merge!(other) ⇒ Object
37 38 39 40 41 |
# File 'lib/zombie_killer/code_histogram.rb', line 37 def merge!(other) counts.merge!(other.counts) do |_key, count, other_count| count + other_count end end |
#print_by_frequency(io) ⇒ Object
17 18 19 20 21 22 23 24 25 |
# File 'lib/zombie_killer/code_histogram.rb', line 17 def print_by_frequency(io) count_to_methods = invert_hash_preserving_duplicates(@counts) count_to_methods.keys.sort.each do |c| count_to_methods[c].sort.each do |method| io.printf("%4d %s\n", c, method) end end end |