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

后端 未结 8 1611
轻奢々
轻奢々 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:02

    puts a.uniq.
           map { | e | [a.count(e), e] }.
           select { | c, _ | c > 1 }.
           sort.reverse.
           map { | c, e | "#{e}:#{c}" }
    

提交回复
热议问题