Question

The question prompt is:

The next keyword can be used to skip over certain steps in the loop. For instance, if we don't want to print out the even numbers, we can write:

i = 20
loop do
  i -= 1
  next if i % 2 == 0
  print "#{i}"
  break if i <= 0
end

Wouldn't this actually print out the even numbers? The way I would read the above is, i = 20, it gets decremented to 19, the if statement is false, so nothing gets printed and the loop cycles once again. This time i = 18, the if statement is true, and 18 gets printed.

But lo and behold, when you do the exercise the above code prints out 19, 17, 15, and so on. What's going on here? Does the decrement occur after the if statement is evaluated?

Thanks in advance.

Was it helpful?

Solution

if statement is false, so nothing gets printed

Why do you think so? When i is 19, the if-statement is false, so it does not skip the iteration, and the print in the next line is executed. When i is 18, the if-statement is true, so it is skipped to the next iteration without executing the print in the next line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top