This blog is part of our Ruby 2.7 series.
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.
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 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.
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 for more details on this.

Written byAkhil Gautam
Related blogs
- 01Ruby 2.7 adds Beginless RangeAugust 25, 2020 · Ashwath Biradar
- 02Ruby 2.7 adds Enumerable#filter_mapMay 8, 2020 · Ashik Salman
- 03Ruby 2.7 adds Enumerator::Lazy#eagerMarch 18, 2020 · Ashik Salman
- 04Ruby 2.7 adds numbered parameters for blocksMarch 3, 2020 · Taha Husain