Codectionary / Developer documentation / Ruby

Counting Values with tally

tally counts equal values and returns a frequency hash. It is available from Ruby 2.7 and avoids manually maintaining a counter for each key. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

items.tally

Examples

Counting Values with tally

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

votes = %w[tea coffee tea tea water]
counts = votes.tally
puts counts.fetch("tea")
puts counts.fetch("coffee")
puts counts.fetch("juice", 0)
  1. Expected output: 3 1 0
  2. The hash contains only encountered values. fetch with a default supplies zero for an absent candidate without inserting it.

Best practices

  • Normalize values before counting when case or whitespace should be ignored.
  • Sort frequencies explicitly when presenting a ranked result.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading