且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何计算Ruby数组中的重复元素

更新时间:2022-06-10 00:07:57

以下代码打印您所要求的内容.我会让您决定如何实际使用来生成您要查找的哈希值:

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.