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

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