How to Remove All Odd Numbers From a Ruby Array?

You can delete all odd numbers from an array in Ruby, by using the Array#delete_if method, for example, like so:

numbers = [5, 10, 26, 44, 75]
numbers.delete_if { | item | item.odd? }

print numbers #=> [10, 26, 44]

This would leave only even numbers in the original array.

You could also shorten this by using the &: syntax, for example, like so:

print numbers.delete_if(&:odd?) #=> [10, 26, 44]

The Array#delete_if method would mutate (i.e. modify) the original array. If you wish to instead return a new array with only even values (in an array of integers), then you can consider using the Array#select method instead.


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.