Quick question

for i in 1…10
next if i % 2 == 0
puts i
end

Output:

1

3

5

7

9

Why doesn’t this code put out the even numbers? To me, it reads if the number is exactly divisible by two print that number. Thanks, C

The for loop iterates over numbers 1 to 9.
The next keyword is used to immediately skip to the next iteration if some condition is satisfied.

If the number is odd, then the condition next if i % 2 == 0 is not satisfied. And we move on to the next statement puts i. This will print the odd number.

If the number is even, then the condition next if i % 2 == 0 is satisfied. And we immediately skip to the next iteration of the loop. We never reach the puts i statement and therefore, the even number isn’t printed.

Ok, thanks, that somewhat makes sense. To clarify . . . if the condition is satisfied the number doesn’t get printed. But if it isn’t satisfied the odd number makes it onto the next line of code and therefore gets printed.

Thanks!

The presence of the next keyword before the condition is important.

If we had something like:

for i in 1...10 
    if i % 2 == 0
        puts i
    end
end

The above would print the even numbers. Notice there is no next keyword and the puts statement is nested in the if block.

Whereas, in the code you have posted, there is a next keyword before the if condition. And the puts statement is not nested in any if block. The puts statement is in the body of the for loop, not in the body of any if block.

for i in 1...10 
    next if i % 2 == 0
    puts i
end

You are correct. If the condition is satisfied, then next takes over and we immediately go to the next iteration of the for loop and the number doesn’t get printed.
If the condition is not satisfied, then next does not come into play. We simply move on to the rest of the statements of the for loop.

1 Like

Thank you, very much.

1 Like