Arnob Arnob - 4 months ago 9
Ruby Question

Why unless returning condition when it is false?

I have the following ruby code block:

x = 1

loop do
x+=1

next unless (x % 2) == 0
puts x


break if x >=10
end

My output:
2
4
6
8
10


Here unless is
(x % 2) ==0
which means when it is false, i.e., x% 2 is gives remainder something other than 0, then it should do
puts
but all the multiples of 2's including 2 itself gives
(x%2)==0
as true. Am I misinterpreting unless statement or anything?

Answer

The next statement means to go back to the beginning of the loop. I think that's what you are missing.

So if x is odd, then (x % 2) == 0 is false, so the next statement is executed, which causes the program to skip running the rest of the loop. This means that odd numbers never get printed.