如何检查 ruby 数组中元素出现的次数

How to check the number of occurrence of an element in a ruby array

我们有一个数组,

a = [1,2,3,2,4,5,2]

现在,我需要一个一个地获取ruby数组中每个元素的出现。所以,这里元素 '1' 的出现次数是 1 次。 '2'出现3次以此类推。

稍后编辑并添加了以下行,因为提交的大部分答案都误解了我的问题:

That means, I need to take the occurrence of a single element at a time.

我怎样才能得到计数?

a = [1,2,3,2,4,5,2]    
p a.inject(Hash.new(0)) { |memo, i| memo[i] += 1; memo }
# => {1=>1, 2=>3, 3=>1, 4=>1, 5=>1}

这是一个典型的 reduce 任务:

a = [1,2,3,2,4,5,2]
a.inject({}) { |memo,e| 
  memo[e] ||= 0
  memo[e] += 1
  memo 
}
#=> {
#  1 => 1,
#  2 => 3,
#  3 => 1,
#  4 => 1,
#  5 => 1
#}

您可以使用enum#reduce

[1,2,3,2,4,5,2].reduce Hash.new(0) do |hash, num|
  hash[num] += 1
  hash
end

输出

{1=>1, 2=>3, 3=>1, 4=>1, 5=>1}

Requires ruby >= 2.2

a.group_by(&:itself).tap{|h| h.each{|k, v| h[k] = v.length}}
# => {1=>1, 2=>3, 3=>1, 4=>1, 5=>1}

我会这样做:

[1,2,3,2,4,5,2].inject(Hash.new(0)) {|h, n| h.update(n => h[n]+1)}
# => {1=>1, 2=>3, 3=>1, 4=>1, 5=>1}

使用 Ruby >= 2.7 你可以调用 .tally:

a = [1,2,3,2,4,5,2]
a.tally
 => {1=>1, 2=>3, 3=>1, 4=>1, 5=>1}