如何计算Ruby数组中的重复元素 [英] How to count duplicate elements in a Ruby array
本文介绍了如何计算Ruby数组中的重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个排序数组:
[
'FATAL <error title="Request timed out.">',
'FATAL <error title="Request timed out.">',
'FATAL <error title="There is insufficient system memory to run this query.">'
]
我想得到类似这样的东西,但它不必是哈希:
I would like to get something like this but it does not have to be a hash:
[
{:error => 'FATAL <error title="Request timed out.">', :count => 2},
{:error => 'FATAL <error title="There is insufficient system memory to run this query.">', :count => 1}
]
推荐答案
以下代码打印您所要求的内容.我会让您决定如何实际使用来生成您要查找的哈希值:
The following code prints what you asked for. I'll let you decide on how to actually use to generate the hash you are looking for:
# sample array
a=["aa","bb","cc","bb","bb","cc"]
# make the hash default to 0 so that += will work correctly
b = Hash.new(0)
# iterate over the array, counting duplicate entries
a.each do |v|
b[v] += 1
end
b.each do |k, v|
puts "#{k} appears #{v} times"
end
注意::我刚刚注意到您说数组已经排序.上面的代码不需要排序.使用该属性可能会产生更快的代码.
Note: I just noticed you said the array is already sorted. The above code does not require sorting. Using that property may produce faster code.
这篇关于如何计算Ruby数组中的重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文