Class: OccurrenceCounter
- Inherits:
-
Object
- Object
- OccurrenceCounter
- Defined in:
- lib/occurrence_counter/occurrence_counter.rb
Instance Attribute Summary collapse
-
#pre_process(*methods) ⇒ Object
readonly
Returns the value of attribute pre_process.
-
#source ⇒ Object
readonly
Returns the value of attribute source.
Class Method Summary collapse
Instance Method Summary collapse
- #count ⇒ Object
-
#initialize(source) ⇒ OccurrenceCounter
constructor
A new instance of OccurrenceCounter.
Constructor Details
#initialize(source) ⇒ OccurrenceCounter
11 12 13 14 15 |
# File 'lib/occurrence_counter/occurrence_counter.rb', line 11 def initialize(source) @source = source @iteration_method = :each @pre_process = [] end |
Instance Attribute Details
#pre_process(*methods) ⇒ Object (readonly)
Returns the value of attribute pre_process.
3 4 5 |
# File 'lib/occurrence_counter/occurrence_counter.rb', line 3 def pre_process @pre_process end |
#source ⇒ Object (readonly)
Returns the value of attribute source.
3 4 5 |
# File 'lib/occurrence_counter/occurrence_counter.rb', line 3 def source @source end |
Class Method Details
.count(source, *pre_process) ⇒ Object
5 6 7 8 9 |
# File 'lib/occurrence_counter/occurrence_counter.rb', line 5 def self.count(source, *pre_process) occurrece_counter = OccurrenceCounter.new(source) occurrece_counter.pre_process(*pre_process) if pre_process.length > 0 occurrece_counter.count end |
Instance Method Details
#count ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/occurrence_counter/occurrence_counter.rb', line 21 def count occurrences = Hash.new(0) @source.send(@iteration_method) do |value| @pre_process.each {|hook| value = (hook.is_a? Proc) ? hook.call(value) : value.send(hook)} # Skip invalid occurrences next if value.nil? occurrences[value] += 1 end occurrences end |