Create a method that counts and outputs an even number from the values in the array. Use the ʻeven? Method` to determine if the value is even.
Output example: count_evens([2, 1, 4, 6]) → 3
def count_evens(nums)
count = 0
nums.each do |num|
if num.even?
count += 1
end
end
puts count
end
variable count
to store an even numbercount
count
at the endIt's a bit confusing compared to Answer 1, but ...
def count_evens(nums)
result = []
nums.each do |num|
if num.even?
result << num
end
end
puts result.length
end
result = []
is an array to hold even valuesresult << num
to put the even number in the array.result.length
outputs how many elements are in the array (that is, even numbers in the array here).ʻOdd? Method` to determine if it is odd
Recommended Posts