如何知道同一对象在数组中出现多少次?我想检查一下找到该对象的次数,例如:
array = ['A','A','A','B','B','C','C','C','D']
因此,A出现了3次,B出现了两次,C也出现了3次,D出现了一次。
我知道如果我使用“ find_all”,例如:
array.find_all{ |e| array.count(e) > 1 }
我会得到答案
["A", "A", "A", "B", "B", "C", "C", "C"]
但是,我该如何计算呢?我想要类似的东西:
A = 3, B = 2, C = 3, D = 1.
您可以在数组上使用注入来遍历数组,并将散列传递给每次迭代以存储数据。因此,要检索给定的数组的数量,请执行以下操作:
array = ["A", "A", "A", "B", "B", "C", "C", "C"]
array.inject(Hash.new(0)) do |hash, array_item|
hash[array_item] += 1
hash # this will be passed into the next iteration as the hash parameter
end
=> {"A"=>3, "B"=>2, "C"=>3}
传递Hash.new(0)
而不是{}
表示您初次遇到时每个键的默认值为0。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句