Exploring Ruby-2.7.0 — Part-Two
Ruby-2.7.0 Adds new method Enumerable#tally
ruby-2.7 has introduced ‘tally’ which returns a hash where the keys are elements and values are the count of occurrence
If you have been programming for a while you might have across a use case where you might have to store the count of elements in array .
Suppose we have an array of outcomes of dice roll and I want to count the distinct occurrence of all possibilities. In ruby-2.7 I could do this
Let us explore some of the implementations in previous versions of ruby.
- Using transform
2. Another variant
3. Using inject
Naturally, among all the variant, the use of “tally” makes it more intuitive and the code more readable.
There are discussions in the community to add a new method ‘tally_by’ which would accept a block . Follow the discussions here about the new feature.
[1, 2, 3].tally_by(&:even?)
Using tally this could be achieved using