class TrickBag::Numeric::MultiCounter
Simplifies accumulating counts of multiple objects. Like a hash, but does not allow []=; increment is the only way to modify a value.
Attributes
Public Class Methods
Creates an instance and iterates over the enumberable, processing all its items.
# File lib/trick_bag/numeric/multi_counter.rb, line 19 def self.from_enumerable(values, name = '') m_counter = MultiCounter.new(name) values.each { |value| m_counter.increment(value) } m_counter end
Creates a multicounter.
@param name optional name for printing in to_s
# File lib/trick_bag/numeric/multi_counter.rb, line 13 def initialize(name = '') @name = name @counts = Hash.new(0) end
Public Instance Methods
Returns the count for the specified key.
# File lib/trick_bag/numeric/multi_counter.rb, line 36 def [](key) @counts[key] end
Adds keys in the passed enumerable to this counter.
# File lib/trick_bag/numeric/multi_counter.rb, line 26 def add_keys(keys) keys.each { |key| @counts[key] = 0 } end
Returns a hash whose keys are the multicounter's keys and whose values are the fraction of total of the values corresponding to those keys.
# File lib/trick_bag/numeric/multi_counter.rb, line 75 def fraction_of_total_hash of_total_hash(:fraction) end
Increments the value corresponding to the specified key.
# File lib/trick_bag/numeric/multi_counter.rb, line 31 def increment(key) @counts[key] += 1 end
Returns whether or not the specified key exists in this counter.
# File lib/trick_bag/numeric/multi_counter.rb, line 46 def key_exists?(key) keys.include?(key) end
Returns this counter's keys.
# File lib/trick_bag/numeric/multi_counter.rb, line 41 def keys @counts.keys end
Returns a hash whose keys are the multicounter's keys and whose values are the percent of total of the values corresponding to those keys.
# File lib/trick_bag/numeric/multi_counter.rb, line 70 def percent_of_total_hash of_total_hash(:percent) end
Creates a hash whose keys are this counter's keys, and whose values are their corresponding values.
# File lib/trick_bag/numeric/multi_counter.rb, line 81 def to_hash @counts.clone end
Returns a string representing this counter, including its values, and, if specified, its optional name.
# File lib/trick_bag/numeric/multi_counter.rb, line 87 def to_s "#{self.class} '#{name}': #{@counts.to_s}" end
Returns the total of all counts.
# File lib/trick_bag/numeric/multi_counter.rb, line 51 def total_count @counts.values.inject(0, &:+) end
Private Instance Methods
Private internal method for use by percent_of_total_hash
and fraction_of_total_hash. @param mode :percent or :fraction
# File lib/trick_bag/numeric/multi_counter.rb, line 58 def of_total_hash(mode = :percent) raise "bad mode: #{mode}" unless [:percent, :fraction].include?(mode) total = total_count keys.each_with_object({}) do |key, ptotal_hash| value = Float(self[key]) / total value *= 100 if mode == :percent ptotal_hash[key] = value end end