How to Remove All Even Numbers From a Ruby Array?

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

You can delete all even 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.even? }

print numbers #=> [5, 75]

This would leave only odd numbers in the original array.

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

print numbers.delete_if(&:even?) #=> [5, 75]

The Array#delete_if method would mutate (i.e. modify) the original array. If you wish to instead return a new array with only odd 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.