How to Get Count of Even/Odd Numbers in a Ruby Array?

In Ruby, you can get the total count of even numbers in an array of integers using the Array#count method (with a condition), for example, like so:

numbers = [5, 10, -26, 44, -75]

puts numbers.count { | item | item.even? } #=> 3
puts numbers.count { | item | item % 2 == 0 } #=> 3

Similarly, to get the total count of odd numbers in an array of integers, you can do the following:

numbers = [5, 10, -26, 44, -75]

puts numbers.count { | item | item.odd? } #=> 2
puts numbers.count { | item | item % 2 == 1 } #=> 2

This post was published (and was last revised ) 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.