我们有一个数组,
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.
我怎么能算上这个?
答案 0 :(得分:5)
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}
答案 1 :(得分:5)
您可以使用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}
答案 2 :(得分:4)
需要
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}
答案 3 :(得分: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
#}
答案 4 :(得分: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}
答案 5 :(得分:0)
使用Ruby> = 2.7时,您可以致电.tally
:
a = [1,2,3,2,4,5,2]
a.tally
=> {1=>1, 2=>3, 3=>1, 4=>1, 5=>1}