Quantcast
Viewing latest article 20
Browse Latest Browse All 42

Answer by Ja͢ck for ruby: how to find non-unique elements in array and print each with number of occurrences?

From Ruby 2.7, you can utilise Enumerable#tally and numbered block arguments:

a = ["a", "d", "c", "b", "b", "c", "c"]puts a.tally.filter { _2 > 1 }.sort_by { -_2 }.map &:first

Here, Enumerable#tally returns a hash like { 'a' => 1, 'b' => 2, ... }, which you then have to filter and sort. After sorting, the hash would've collapsed to a nested array, e.g. [['b', 2], ...]. The last step is to take the first argument of each array element, using &:first.


Viewing latest article 20
Browse Latest Browse All 42

Trending Articles