Class: Counter
- Inherits:
-
Hash
- Object
- Hash
- Counter
- Defined in:
- lib/counter.rb
Instance Method Summary collapse
- #+(rhs) ⇒ Object
- #-(rhs) ⇒ Object
-
#initialize(other = nil) ⇒ Counter
constructor
A new instance of Counter.
- #inspect ⇒ Object
- #most_common(n = nil) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(other = nil) ⇒ Counter
Returns a new instance of Counter.
2 3 4 5 6 7 |
# File 'lib/counter.rb', line 2 def initialize(other = nil) super(0) other.each { |e| self[e] += 1 } if other.is_a? Array other.each { |k, v| self[k] = v } if other.is_a? Hash other.each_char { |e| self[e] += 1 } if other.is_a? String end |
Instance Method Details
#+(rhs) ⇒ Object
9 10 11 12 13 14 15 |
# File 'lib/counter.rb', line 9 def +(rhs) raise TypeError, "cannot add #{rhs.class} to a Counter" unless rhs.is_a? Counter result = Counter.new(self) rhs.each { |k, v| result[k] += v } result end |
#-(rhs) ⇒ Object
17 18 19 20 21 22 23 |
# File 'lib/counter.rb', line 17 def -(rhs) raise TypeError, "cannot subtract #{rhs.class} to a Counter" unless rhs.is_a? Counter result = Counter.new(self) rhs.each { |k, v| result[k] -= v } result end |
#inspect ⇒ Object
34 35 36 |
# File 'lib/counter.rb', line 34 def inspect to_s end |
#most_common(n = nil) ⇒ Object
25 26 27 28 |
# File 'lib/counter.rb', line 25 def most_common(n = nil) s = sort_by { |_k, v| -v } n ? s.take(n) : s end |
#to_s ⇒ Object
30 31 32 |
# File 'lib/counter.rb', line 30 def to_s "Counter(#{super})" end |