We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
Ruby 2.7.0 was released on Dec 25, 2019.
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
.
1irb> scores = [100, 35, 70, 100, 70, 30, 35, 100, 45, 30]
2
3# we can use group_by to group the scores
4
5irb> scores.group_by { |v| v }.map { |k, v| [k, v.size] }.to_h
6=> {100=>3, 35=>2, 70=>2, 30=>2, 45=>1}
7
8# or we can use inject to group the scores
9
10irb> scores.inject(Hash.new(0)) {|hash, score| hash[score] += 1; hash }
11=> {100=>3, 35=>2, 70=>2, 30=>2, 45=>1}
12
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.
1
2irb> scores = [100, 35, 70, 100, 70, 30, 35, 100, 45, 30]
3irb> scores.tally
4=> {100=>3, 35=>2, 70=>2, 30=>2, 45=>1}
5
Check out the github commit for more details on this.