Ruby 提供豐富的迴圈構造,本文整理 while/until、for...in、流程控制 (break/next/redo/retry)、Integer 迭代器 (times/upto/downto/step)、Enumerable#each 等語法與適用場景。
# while 條件為真執行
while condition
stmt1; stmt2
end
# 單行 while
(stmt1; stmt2) while condition
# until 條件為假執行 (等同 while !condition)
until condition
stmt
end
# for...in 遍歷任何回應 each 的物件
for var in collection
stmt
end
| 關鍵字 | 行為 |
|---|---|
break | 跳出**當層**迴圈 |
next | 跳過本次迴圈剩餘,進入下一次 |
redo | 重新開始**本次**迴圈 (不重新評估條件/迭代器) |
retry | 重新開始**整個**迴圈體 (重新評估迭代器/條件) |
3.times { print "Hi! " } # Hi! Hi! Hi!
1.upto(9) { |i| print i if i < 7 } # 123456
9.downto(1) { |i| print i if i < 7 } # 654321
(1..9).each { |i| print i if i < 7 } # 123456
0.step(11, 3) { |i| print i } # 0 3 6 9
n.times、upto/downto、step。collection.each { |e| ... } (最通用、可鏈式 map/select)。each_with_index 或 .with_index。for...in:它不建立新作用域,區塊變數會洩漏到外層;each 區塊變數區域化。redo/retry 極少用,僅用於輸入驗證重試等特殊邏輯,濫用極難維護。