문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top