How to Count Occurrences of a Value in a Ruby Array?

In Ruby, you can count the total number of times a value appears in an array by passing it as an argument to the Array#count method.

For example, to count the occurrences of the integer 3 in an array of integers, you would do the following:

puts [3, 3, 4, 3, 3, 5, 5].count(3) #=> 4

It works the same way for values of other types as well. For example:

puts [nil, nil, 4, nil, nil, 5, 5].count(nil) #=> 4

puts ["foo", "bar", "foobar", "foo", "baz"].count("foo") #=> 2

puts [true, true, false, true].count(true) #=> 3

# ...

When the value does not exist in an array, as you would expect, 0 is returned:

puts [1, 3, 3, 4, 3, 3, 5, 5, 6].count(2) #=> 0

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.