---
title: "Ruby 2.7 adds Enumerable#tally"
description: "Ruby 2.7 adds Enumerable#tally"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-7-adds-enumerable-tally"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-7-adds-enumerable-tally.md"
---

# Ruby 2.7 adds Enumerable#tally

Ruby 2.7 adds Enumerable#tally

- Author: Akhil Gautam
- Published: February 18, 2020
- Categories: Ruby 2.7, Ruby

Let's say that we have to find the frequency of each element of an array.

Before Ruby 2.7, we could have achieved it using `group_by` or `inject`.

```ruby
irb> scores = [100, 35, 70, 100, 70, 30, 35, 100, 45, 30]

# we can use group_by to group the scores

irb> scores.group_by { |v| v }.map { |k, v| [k, v.size] }.to_h
=> {100=>3, 35=>2, 70=>2, 30=>2, 45=>1}

# or we can use inject to group the scores

irb> scores.inject(Hash.new(0)) {|hash, score| hash[score] += 1; hash }
=> {100=>3, 35=>2, 70=>2, 30=>2, 45=>1}

```

#### Ruby 2.7

Ruby 2.7 adds `Enumerable#tally` which can be used to find the frequency.
`Tally` makes the code more readable and intuitive. It returns a hash where keys
are the unique elements and values are its corresponding frequency.

```ruby

irb> scores = [100, 35, 70, 100, 70, 30, 35, 100, 45, 30]
irb> scores.tally
=> {100=>3, 35=>2, 70=>2, 30=>2, 45=>1}

```

Check out the
[github commit](https://github.com/ruby/ruby/commit/673dc51c251588be3c9f4b5b5486cd80d46dfeee)
for more details on this.

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-7-adds-enumerable-tally)
