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

Count how many times an element appears 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

Hope you found this post useful. It was published . Please show your love and support by sharing this post.