萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 迴圈語法完整速查表

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重新開始**整個**迴圈體 (重新評估迭代器/條件)

Integer 迭代器 (效能最佳、語意清晰)


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 極少用,僅用於輸入驗證重試等特殊邏輯,濫用極難維護。
copyright © 萬盛學電腦網 all rights reserved