---
title: Count occurrences with the .tally method
author: Daniel Schoppmann
tags: Ruby
published_at: '2024-02-08T18:01:00+01:00'
updated_at: '2024-07-18T09:09:53+02:00'
canonical_url: https://www.dotruby.com/articles/count-occurrences-with-the-tally-method
---

# Count occurrences with the .tally method

Learn how to leverage the universal `tally` method for easy counting.

You might know that Rails turns an ActiveRecord Relation filled with a `.group` and a `.count` call in a very handy Hash result object, where each grouped attribute is the key and the value is the direct count of the attributes's ocurances. 

```ruby
Post.group(:state).count 
=> {"draft" => 2, "published" => 5}
```

Ruby itself provides a similar functionality with the `.tally` method which is available in the Enumarable module. So whenever you have an array e.g. it’s now super easy to get the count of each element occurances within the array. The method has been in the standard lib since Ruby 2.7. 

```ruby
array = %w(draft published published draft published)
array.tally
=> {"draft" => 2, "published" => 3}
```
