Reputation: 6928
We have an array,
a = [1,2,3,2,4,5,2]
Now, I need to get the occurrence of each element in the ruby array one by one. So, here the ocuurrence of element '1' is 1 times. Occurrence of '2' is 3 times and so on.
Edited and added the below line later as most of the answers were submitted misinterpreting my question:
That means, I need to take the occurrence of a single element at a time.
How I could get the count?
Upvotes: 1
Views: 1416
Reputation: 1191
With Ruby >= 2.7 you can call .tally
:
a = [1,2,3,2,4,5,2]
a.tally
=> {1=>1, 2=>3, 3=>1, 4=>1, 5=>1}
Upvotes: 1
Reputation: 168269
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}
Upvotes: 4
Reputation: 107142
I would do something like this:
[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}
Upvotes: 1
Reputation: 135415
You can use enum#reduce
[1,2,3,2,4,5,2].reduce Hash.new(0) do |hash, num|
hash[num] += 1
hash
end
Output
{1=>1, 2=>3, 3=>1, 4=>1, 5=>1}
Upvotes: 5
Reputation: 121010
That’s a typical reduce
task:
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
#}
Upvotes: 1
Reputation: 15791
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}
Upvotes: 5