How to Return All Even Numbers in a Ruby Array?

Find all even numbers in a Ruby array

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]

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