How to Count Values in a Ruby Array That Satisfy a Condition?

In Ruby, you can count the total number of times a value appears in an array based on a condition, by calling Array#count method with a block (i.e. code within {...}):

array.count { |item| condition }

For example, to count the number of items less than 4 in an array of integers, you could do the following:

numbers = [3, 2, 5, 6, 1, 7, 8]

puts numbers.count { | item | item < 4 } #=> 3

It works the same way for values of other types as well. For example, the following counts the number of strings in the array that contain the word "foo".

strings = ["foo", "bar", "foobar", "foo", "baz"]

puts strings.count { | item | item.include?("foo") } #=> 3

When no values matching the criteria are found in the array, 0 is returned:

numbers = [1, 3, 3, 4, 3, 3, 5, 5, 6]

puts numbers.count { | item | item < 0 }  #=> 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.