I am reviewing the drill to strengthen my logical thinking. As a beginner, I would appreciate it if you could let me know if you have any questions.
From the values in the array, let's create a method that counts and outputs an even number using the even? method.
count_evens([2, 1, 2, 3, 4]) → 3 count_evens([2, 2, 0]) → 3 count_evens([1, 3, 5]) → 0
def count_evens(nums)
count = 0 #③
nums.each do |num| #①
if num.even? #②
count += 1
end
end
puts count #④
end
Fetch the values in the array one by one.
nums
is taken out one by one with each and assigned to num
.
If num
is an even number, it is counted by count + = 1
.
If it is an even number, the even?
method determines.
In order to count in (2), it is necessary to prepare a variable, so set count = 0
.
One thing to note here is the location.
If you put it in an if statement or each statement, count = 0
will be executed every time it is processed, so be sure to put it outside the each statement.
Like count = 0
, put puts
outside the each statement so that it is output only once at the end.
The processing of each statement is completed, and the final number assigned to count
becomes an even number.
Recommended Posts