Rajesh Omanakuttan
Rajesh Omanakuttan

Reputation: 6928

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

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

Answers (6)

Andrei
Andrei

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

sawa
sawa

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

spickermann
spickermann

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

Mulan
Mulan

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

Aleksei Matiushkin
Aleksei Matiushkin

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

Rustam Gasanov
Rustam Gasanov

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

Related Questions