class Counter
Public Class Methods
new(other = nil)
click to toggle source
Calls superclass method
# 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
Public Instance Methods
+(rhs)
click to toggle source
# 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)
click to toggle source
# 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()
click to toggle source
# File lib/counter.rb, line 34 def inspect to_s end
most_common(n = nil)
click to toggle source
# 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()
click to toggle source
# File lib/counter.rb, line 30 def to_s "Counter(#{super})" end