1

How to know how many times the same Object appears in Array? I want to check how many times I found the object, like:

array = ['A','A','A','B','B','C','C','C','D']

So, A appeared three times, B twice, C three too, and only one for D.

I know that if I use "find_all", like:

array.find_all{ |e| array.count(e) > 1 }

I will get with answer

["A", "A", "A", "B", "B", "C", "C", "C"]

but, how I can count this? I want something like:

 A = 3, B = 2, C = 3, D = 1.

1 Answer 1

1

You can use inject on the array to iterate over the array and pass a hash into each iteration to store data. So to retrieve the count of the array you gave you would do this:

array = ["A", "A", "A", "B", "B", "C", "C", "C"]
array.inject(Hash.new(0)) do |hash, array_item| 
  hash[array_item] += 1
  hash # this will be passed into the next iteration as the hash parameter
end

=> {"A"=>3, "B"=>2, "C"=>3}

Passing in Hash.new(0) rather than {} will mean that the default value for each key when you first encounter it will be 0.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.