Syntax
items.tallyExamples
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)- Expected output: 3 1 0
- 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