I have
a = [\"a\", \"d\", \"c\", \"b\", \"b\", \"c\", \"c\"]
and need to print something like (sorted descending by 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
.