Class: Counter

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

Overview

Basic counting.

To count:

Easiest way to count is to increment while iterating over data:

c = Counter.new
c.increment('some-key')
c.saw('some-key')  # alias

But you can also set counts directly:

c = Counter.new
c.set('another-key', 42)

To get counts back:

You can use Hash-style syntax:

puts c['some-key]
=> 2

or ask for the top-n keys as an array of [key, count]

puts c.top(2)
=> [['key-1',50],['key-2',38]]

or just ask for data for all keys:

puts c.counts
=> [['key-1',50],['key-2',38],['key-3',22]]

Some notes

  • 0 is returned, even if key has never been seen

  • if ties exist in a top-n ranking, they are broken by sort on key

Instance Method Summary collapse

Constructor Details

#initializeCounter

Returns a new instance of Counter.



35
36
37
# File 'lib/counter/counter.rb', line 35

def initialize
  @data = Hash.new(0)
end

Instance Method Details

#[](key) ⇒ Object

Retrieve the count for a particular key



53
54
55
# File 'lib/counter/counter.rb', line 53

def [] key
  @data[key]
end

#countsObject

Returns all elements as [key, count] array



58
59
60
# File 'lib/counter/counter.rb', line 58

def counts
  sorted_data
end

#increment(key) ⇒ Object Also known as: saw

key++



40
41
42
43
# File 'lib/counter/counter.rb', line 40

def increment key
  @data[key] += 1
  true
end

#set(key, count) ⇒ Object

sets the key to a specified value

Raises:

  • (ArgumentError)


47
48
49
50
# File 'lib/counter/counter.rb', line 47

def set key, count
  raise ArgumentError, "count must be numeric" if !count.is_a?(Numeric)
  @data[key] = count
end

#to_aObject



67
68
69
# File 'lib/counter/counter.rb', line 67

def to_a
  @data.to_a
end

#top(n) ⇒ Object

Returns top n elements as [key,count] array



63
64
65
# File 'lib/counter/counter.rb', line 63

def top n
  sorted_data[0,n]
end