Class: Counter

Inherits:
Hash
  • Object
show all
Defined in:
lib/counter.rb

Instance Method Summary collapse

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

Raises:

  • (TypeError)


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

Raises:

  • (TypeError)


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

#inspectObject



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_sObject



30
31
32
# File 'lib/counter.rb', line 30

def to_s
  "Counter(#{super})"
end