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

Default Enum in Rails 6
Rails 6 provides a way to define default enum value. Let’s see how it works...
How to rename column name in Rails
Rails rename_column Rails provides a simple method rename_column which can be used in a migration....
How to use Enum in Rails
Enum in Rails “Enum” for short for the word “Enumerator” is widely used in different...