1loops.rb
    1. $hours_asleep = 0
    2. def tired
    3. if $hours_asleep >= 8 then
    4. $hours_asleep = 0
    5. return false
    6. else
    7. $hours_asleep += 1
    8. return true
    9. end
    10. def snore
    11. puts('snore....')
    12. end
    13. def sleep
    14. puts("z" * $hours_asleep )
    15. end
    16. while tired do sleep end # a single-line while loop
    17. while tired # a multi-line while loop
    18. sleep
    19. end
    20. sleep while tired # single-line while modifier
    21. begin # multi-line while modifier
    22. sleep
    23. snore
    24. end while tired
    通常 while 循环会执行 0 次或多次,因为布尔测试先于循环体执行;如果布尔测试在开始时就返回 false,则循环体内的代码永远不会运行。但是,当 while 循环属于 begin 和 包裹的代码块类型时,循环将执行 1 次或多次,因为循环体内的代码先于布尔表达式执行。
    2loops.rb
    要了解这两种类型的 while 循环的行为差异,请运行 2loops.rb。这些示例应该有助于阐明该问题: x = 100 # The code in this loop never runs while (x < 100) do puts(‘x < 100’) end # The code in this loop never runs puts(‘x < 100’) while (x < 100) # But the code in loop runs once begin puts(‘x < 100’) end while (x < 100)