Count occurrences with the .tally method.

Published on February 08, 2024
Written by Daniel Schoppmann

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.

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.

array = %w(draft published published draft published)
array.tally
=> {"draft" => 2, "published" => 3}
Subscribe to get future articles via the RSS feed .