In Ruby, you can get all odd numbers in an array of integers by using the Array#select
method. This would return a new array containing all odd numbers:
numbers = [-5, -2, -1, 0, 1, 3, 4, 7] odd_numbers = numbers.select { | item | item.odd? } print odd_numbers #=> [-5, -1, 1, 3, 7] print numbers #=> [-5, -2, -1, 0, 1, 3, 4, 7]
As you can see in the example above, the original array is unchanged.
You could also shorten this by using the &:
syntax, for example, like so:
print numbers.select(&:odd?) #=> [-5, -1, 1, 3, 7]
When no matches are found, an empty array is returned:
numbers = [-2, 0, 4] odd_numbers = numbers.select { | item | item.odd? } print odd_numbers #=> []
As an alternative to using the Integer#odd?
method, you can also use the modulus operator to filter by odd numbers, for example, like so:
print numbers.select { | item | item % 2 == 1 } #=> [-5, -1, 1, 3, 7]
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.