Exploring Ruby-2.7.0 — Part-Two

Tessy Joseph
The MavenHive Blog
Published in
1 min readJun 6, 2019

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

count occurrence of each face in a dice roll using tally

Let us explore some of the implementations in previous versions of ruby.

  1. Using transform
count occurrence of each face in a dice roll using transform_by

2. Another variant

3. Using inject

count occurrence of each face in a dice roll 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

count of even numbers using tally

--

--