1

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?

1
  • 1
    You changed the question, so all answers apart of yours became invalid...? Commented Jan 28, 2015 at 7:04

6 Answers 6

5

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}
Sign up to request clarification or add additional context in comments.

Comments

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}

Comments

4

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}

3 Comments

hm, never heard about itself, I get undefined method 'itself' for 1:Fixnum with Ruby 2.1
@RustamA.Gasanov, that's because you're not using the latest and greatest. Object#itself, which has been in the works for some time, has finally arrived in v.2.2! Hurray!
@CarySwoveland ah, you meant 2.2, I see:) thank you, I should take a look
1

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
#}

2 Comments

Perhaps use Enumerable#each_with_object to avoid the need to return memo.
@CarySwoveland yes, but this is definitely a task for reduce. So I decided to be more clear at the expense of shortness.
1

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}

3 Comments

I didn't know you could dispense with the braces there. h.update n => h[n]+1 looks even stranger.
@CarySwoveland : Where would you add braces? Hash#update returns self, that avoids the need to return the memo.
Here: {n => h[n]+1}. I forgot that Ruby allows a hash to be passed as an argument without the braces.
1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.