---
title: "Ruby 3.1 accumulates Enumerable#tally results"
description: "Ruby 3.1 accumulates Enumerable#tally results"
canonical_url: "https://www.bigbinary.com/blog/ruby-3-1-accumulates-enumerable-tally-results"
markdown_url: "https://www.bigbinary.com/blog/ruby-3-1-accumulates-enumerable-tally-results.md"
---

# Ruby 3.1 accumulates Enumerable#tally results

Ruby 3.1 accumulates Enumerable#tally results

- Author: Ashik Salman
- Published: April 20, 2021
- Categories: Ruby 3.1, Ruby

We already know the
[Enumerable#tally](https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-tally)
method is used to count the occurrences of each element in an `Enumerable`
collection. The `#tally` method was introduced in ruby 2.7.0. Please check
[our blog](https://bigbinary.com/blog/ruby-2-7-adds-enumerable-tally) for more
details on it.

Ruby 3.1 introduces an optional hash argument for the `Enumerable#tally` method
to count. If a hash is given, the total number of occurrences of each element is
added to the hash values and the final hash is returned.

## Ruby 2.7.0+

```ruby
=> letters = ["a", "b", "c", "a", "d", "c", "a", "c", "a"]
=> result = letters.tally
=> {"a"=>4, "b"=>1, "c"=>3, "d"=>1}
```

## Before Ruby 3.1

```ruby
=> new_letters = ["a", "b", "c", "a", "c", "a"]
=> new_letters.tally(result)
=> ArgumentError (wrong number of arguments (given 1, expected 0))
```

## After Ruby 3.1

```ruby
=> new_letters = ["a", "b", "c", "a", "c", "a"]
=> new_letters.tally(result)
=> {"a"=>7, "b"=>2, "c"=>5, "d"=>1}
```

The value corresponding to each element in the hash must be an integer.
Otherwise, the method raises `TypeError` on execution.

If the default value is defined for the given hash, it will be ignored and the
count of occurrences will be added in the returned hash.

```ruby
=> letters = ["a", "b", "c", "a"]
=> letters.tally(Hash.new(10))
=> {"a"=>2, "b"=>1, "c"=>1}
```

Here's the relevant [pull request](https://github.com/ruby/ruby/pull/4318) and
[feature discussion](https://bugs.ruby-lang.org/issues/17744) for this change.

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-3-1-accumulates-enumerable-tally-results)
