红宝石:如何找到数组中的非唯一元素并用出现次数打印每个元素? [英] ruby: how to find non-unique elements in array and print each with number of occurrences?
本文介绍了红宝石:如何找到数组中的非唯一元素并用出现次数打印每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
a = ["a", "d", "c", "b", "b", "c", "c"]
,并且需要打印类似的内容(按出现的次数降序排列):
and need to print something like (sorted descending by number of occurrences):
c:3
b:2
我了解第一部分(发现不唯一)是:
I understand first part (finding NON-unique) is:
b = a.select{ |e| a.count(e) > 1 }
=> ["c", "b", "b", "c", "c"]
或
puts b.select{|e, c| [e, a.count(e)] }.uniq
c
b
如何输出出现次数倒退的每个非唯一变量?
How to output each non-unique with number of occurrences sorted backwards?
推荐答案
puts a.uniq.
map { | e | [a.count(e), e] }.
select { | c, _ | c > 1 }.
sort.reverse.
map { | c, e | "#{e}:#{c}" }
这篇关于红宝石:如何找到数组中的非唯一元素并用出现次数打印每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文