How to Remove All Even Numbers From a Ruby Array?

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.

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.