ruby: how to find non-unique elements in array and print each with number of occurrences?

后端 未结 8 1437
轻奢々
轻奢々 2020-12-31 03:54

I have

a = [\"a\", \"d\", \"c\", \"b\", \"b\", \"c\", \"c\"]

and need to print something like (sorted descending by number of occurrences)

8条回答
  •  离开以前
    2020-12-31 04:04

    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.

提交回复
热议问题