Lines 4 & 5 are causing me grief:
1 def test_break_statement
2 i = 1
3 result = 1
4 while true
5 break unless i <= 10
6 result = result * i
7 i += 1
8 end
9 assert_equal 3628800, result
10 end
I’m not sure what needs to remain true in the while true statement, however I believe it is the code that follows it. This leads to further confusion because I am reading the line:
break unless i <= 10 as break if i is not smaller or equal to 10. What procedure is this code going through ie how does the while and break statements interplay. I think I am nearly there but can’t put the process in my head. Thanks.
whilestatements test whatever comes after the wordwhile.If the expression that follows them istruethey execute the code within the loop. If the expression is false, they do not.Thus, as other posters have pointed out,
while truewill always execute the code within the loop. Luckily for your code there is abreakstatement within the loop. If there wasn’t, the loop would run forever and you’d have to kill the process running your program.In your code sample the
breakkeyword is followed byunlesswhich means that it willbreakthe loopunlessthe expression following it is true. Your code will break out of the loop when i is greater than 10.