Ruby 2.7 adds Enumerable#tally



After introducing the Enumerable#tally method in Ruby 2.7-preview updates.

#tally as the name suggests gives out the number of occurrences of elements.

Before #tally

  elements = [2, 3, 2, 4, 1]

  tally_hash = Hash.new(0)

  elements.each { |number| tally_hash[number] += 1 }

  tally_hash
  # => { 2 => 2, 3 => 1, 4 => 1, 1 => 1 }

Ruby 2.7

More clean and elegant solution

  elements = [2, 3, 2, 4, 1]
  
  elements.tally 
  # => { 2 => 2, 3 => 1, 4 => 1, 1 => 1 }

Evolution of #tally is #tally_by that we discussed earlier in our Ruby 2.7 Preview blog.

Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...