class

Collections::Counter(T)

Inherits Enumerable < Reference < Object

A multiset / tally that counts occurrences of values, inspired by Python's collections.Counter. Missing keys read as 0, and reading a key never creates an entry.

counter = Collections::Counter(Char).new("mississippi".chars)
counter['s']           # => 4
counter['z']           # => 0
counter.most_common(2) # => [{'i', 4}, {'s', 4}]

Constructors

new(elements : Enumerable(T))

Builds a counter by tallying the occurrences of each element.

Source

Instance methods

+(other : Counter(T)) : Counter(T)

Returns a new counter with the counts of both summed. Only keys with a positive total are kept, matching Python's Counter + Counter.

Source
-(other : Counter(T)) : Counter(T)

Returns a new counter with other's counts subtracted. Only keys with a positive result are kept, matching Python's Counter - Counter.

Source
<<(key : T) : self

Increments key by one. Returns self so calls can be chained.

Source
==(other : Counter(T)) : Bool

Compares the stored counts exactly. Note that an explicit zero count is not treated as an absent key here.

Source
[](key : T) : Int64

Returns the count for key, or 0 if it is absent.

Source
[]=(key : T, count : Int) : Int64

Sets the count for key explicitly. Zero and negative counts are allowed.

Source
delete(key : T) : Int64 | Nil

Removes key entirely, returning its previous count (or nil if absent).

Source
each

Must yield this collection's elements to the block.

Source
elements

Returns each key repeated by its count. Keys with a count of 0 or less are skipped.

Source
empty?

Returns true if self does not contain any element.

([] of Int32).empty? # => true
([1]).empty?         # => false
[nil, false].empty?  # => false
  • #present? returns the inverse.
Source
increment(key : T, by : Int = 1) : Int64

Adds by (default 1) to key's count and returns the new count. Counts are stored as Int64, so large accumulated totals do not overflow.

Source
keys
Source
most_common(n : Int32 | Nil = nil) : Array(Tuple(T, Int64))

Returns the n highest-count entries as {key, count} pairs, most common first. With no argument, returns every entry sorted by count descending. Ties between equal counts are returned in an unspecified order.

Source
size

Returns the number of elements in the collection.

[1, 2, 3, 4].size # => 4
Source
to_h

Creates a Hash out of an Enumerable where each element is a 2 element structure (for instance a Tuple or an Array).

[[:a, :b], [:c, :d]].to_h        # => {:a => :b, :c => :d}
Tuple.new({:a, 1}, {:c, 2}).to_h # => {:a => 1, :c => 2}
Source
total

Returns the sum of all counts.

Source
values
Source