How to Remove All Odd Numbers From a Ruby Array?

Find out how to delete all odd numbers from an array of integers in Ruby

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.

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