0
0
RubyHow-ToBeginner · 3 min read

How to Use Tally in Ruby: Count Elements Easily

In Ruby, tally is a method that counts how many times each element appears in an array or enumerable and returns a hash with elements as keys and counts as values. You simply call tally on an array or enumerable to get this count.
📐

Syntax

The tally method is called on an array or any enumerable object. It returns a hash where each key is an element from the array, and the value is the number of times that element appears.

Syntax:

enumerable.tally

Here, enumerable can be an array or any enumerable object.

ruby
array = [1, 2, 2, 3, 3, 3]
counts = array.tally
puts counts
Output
{1=>1, 2=>2, 3=>3}
💻

Example

This example shows how to use tally to count the frequency of words in an array.

ruby
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = words.tally
puts word_counts
Output
{"apple"=>3, "banana"=>2, "orange"=>1}
⚠️

Common Pitfalls

One common mistake is trying to use tally on a hash or non-enumerable object, which will cause an error. Also, tally only works on Ruby 2.7 and later versions.

Another pitfall is expecting tally to sort the results; it does not sort the hash keys.

ruby
wrong = {a: 1, b: 2}
# wrong.tally # This will raise NoMethodError

# Correct usage:
array = [:a, :b, :a]
puts array.tally
Output
{:a=>2, :b=>1}
📊

Quick Reference

MethodDescription
tallyCounts occurrences of each element in an enumerable and returns a hash
tally { |item| block }Counts occurrences based on the block's return value (Ruby 3.1+)
Works on arrays and enumerablesOnly available in Ruby 2.7 and later

Key Takeaways

Use tally on arrays or enumerables to count element frequencies easily.
tally returns a hash with elements as keys and their counts as values.
tally requires Ruby 2.7 or newer to work.
It does not sort the results; sorting must be done separately if needed.
Avoid calling tally on non-enumerable objects like hashes.