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