I encountered the first behavior while using while, so make a note of it.
ruby: 2.7.1
a = 0
while
if a == 5
break
end
a += 1
end
puts a
#Execution result: 0
b = 0
while
b += 1
if b == 5
break
end
end
puts b
#Execution result: 5
c = 0
while c < 5 do
c += 1
end
puts c
#Execution result: 5
d = 0
loop do
if d == 5
break
end
d += 1
end
puts d
#Execution result: 5
e = 0
loop do
e += 1
if e == 5
break
end
end
puts e
#Execution result: 5
As a result I expected, I thought that 5
would output even with phenomenon _A.
(It was solved by @ scivola's comment.)
Apparently, the expression immediately after while
is evaluated as a conditional expression. In other words, in this phenomenon_A,
if a == 5
break
end
This part is evaluated for the first time as a conditional expression of while
, and of course ʻa == 5 becomes
false and the value of ʻif
expression becomes nil
, so it seems that it has escaped from the loop.
By the way, in Ruby, all values except nil
and false
are true
.
When I gave a conditional expression as follows, the processing in the loop was executed.
a = 0
while true do #do is optional
if a == 5
break
end
a += 1
end
puts a
#Execution result: 5
The pitfall of this time was that the expression inside the loop was actually a conditional expression.
2020/07/04 17:11 In the comment, @scivola explained the cause of the problem, so I edited "Why this happens". 2020/07/04 17:31 I changed the title to match the content and proofread the text a little.
I don't usually use while
or loop
, but use another iterative method.
Recommended Posts