how to find even number in an array ruby
To find even numbers in an array in Ruby, you can follow these steps:
Initialize an empty array: Create an empty array to store the even numbers that are found in the input array.
Iterate over the input array: Use a loop to go through each element in the input array.
Check if the number is even: For each element in the array, use the modulo operator (
%
) to check if it is divisible by 2 without any remainder. If the remainder is 0, then the number is even.Add even numbers to the result array: If a number is even, append it to the result array that was initialized in step 1.
Return the result array: After iterating through all the elements in the input array, return the result array that contains the even numbers.
Here is an example code snippet that demonstrates these steps:
def find_even_numbers(array)
result = []
array.each do |number|
if number % 2 == 0
result << number
end
end
return result
end
# Example usage:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = find_even_numbers(numbers)
puts even_numbers
In this example, the find_even_numbers
method takes an array as an argument and returns a new array containing the even numbers. The each
method is used to iterate over each element in the input array, and the modulo operator (%
) is used to check if each number is even. If a number is even, it is added to the result
array. Finally, the result
array is returned and printed using puts
.