Quantcast
Channel: User Ja͢ck - Stack Overflow
Viewing all articles
Browse latest Browse all 44

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

$
0
0

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 all articles
Browse latest Browse all 44


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>