Ruby 循环
系统讲解 while/until 语句及 begin...end 后置修饰符、for...in 与 .each 作用域差异,以及 break、next、redo 与现代 Ruby retry 的精确语义。
学完这一章,你能够
- 系统讲解 while/until 语句及 begin...end 后置修饰符、for...in 与 .each 作用域差异,以及 break、next、redo 与现代 Ruby retry 的精确语义。
while / until 循环及其修饰符形式
`while conditional [do] ... end` 在条件为真时重复执行循环体(多行时可省略 `do`,单行写法需用 `do` 或分号分隔;早期冒号 `:` 分隔语法已在 Ruby 1.9+ 移除)。当 `$i = 0`、`$num = 5` 且条件为 `$i < $num` 时,循环依次输出 `0` 到 `4`。
后置形式 `code while condition` 在条件为真时执行;若将 `while` 修饰符置于不含 `rescue`/`ensure` 的 `begin ... end` 块之后(`begin ... end while conditional`),则会先执行一次循环体再判断条件(类似其他语言的 `do-while`;不过现代 Ruby 社区及 Matz 均更推荐用 `loop do ... break unless cond end` 替代,避免视觉误解)。
`until` 与 `while` 条件取反:当条件为假时持续执行,直到条件变为真时终止。例如 `until $i > $num`(`$num = 5`)会输出 `0` 到 `5` 共 6 次;其后置修饰符 `code until cond` 与 `begin ... end until cond` 同样遵循“先执行一次再检查条件”的边界规则。
for...in 循环与 .each 作用域对比
`for i in 0..5 ... end` 会对右侧可迭代对象逐元素执行循环体(同样支持单行 `do` 写法),在迭代结果上等价于 `(0..5).each do |i| ... end`,都会输出 `0` 到 `5`。两者的关键区别在于作用域:**`for` 循环不会创建新的局部变量作用域**,循环结束后变量 `i` 仍滞留在外层作用域并保留末值 `5`;而 `.each` 块参数 `|i|` 仅在块内局部可见,不会污染外部环境,因此惯用 Ruby 代码普遍优先使用 `.each`。
循环控制:break、next、redo 与 retry 规范
`break` 立即终止最内层循环(在块中调用会退出对应迭代方法并默认返回 `nil`,也可写作 `break val` 带回自定义值),例如 `i > 2` 时 `break` 仅输出 `0, 1, 2`;`next` 跳过本次剩余语句直接进入下一轮迭代(在块中使当前 `yield` 求值为 `nil`),例如 `i < 2` 时 `next` 会输出 `2, 3, 4, 5`。
`redo` 在不重新检查循环条件也不推进迭代器的情况下重跑当前这一轮迭代——若像无守卫示例那样始终满足 `i < 2` 并无条件 `redo`,就会反复打印 `0` 陷入死循环,实际使用时必须搭配状态变更或最大重试次数守卫。关于 `retry`,务必注意**自 Ruby 1.9 起(含 Ruby 3.x)已明确禁止在普通循环与迭代块中使用 `retry`**(会直接报 `SyntaxError: Invalid retry`);现代 Ruby 中 `retry` 仅允许出现在 `begin ... rescue` 异常处理子句内,用于从 `begin` 开头重新尝试受保护代码块。
离线校验 while/until 修饰符、for 与 each 作用域差异、break/next 及受控 redo/rescue retry
展开查看收起
"""Offline Ruby 3.x semantic verification lab for Chapter 17 (loop)."""
import json
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_while_until_and_begin_end_modifiers():
# while $i < 5 -> 0..4; until $i > 5 -> 0..5
i, while_vals = 0, []
while i < 5:
while_vals.append(i)
i += 1
i, until_vals = 0, []
while not (i > 5):
until_vals.append(i)
i += 1
# begin ... end while false executes body once before checking condition
exec_once = 0
while True:
exec_once += 1
if not False:
break
expected = {
"while_vals": [0, 1, 2, 3, 4],
"until_vals": [0, 1, 2, 3, 4, 5],
"begin_end_while_min_runs": 1,
}
actual = {
"while_vals": while_vals,
"until_vals": until_vals,
"begin_end_while_min_runs": exec_once,
}
return {
"name": "while_until_and_begin_end_modifiers",
"summary": "验证 while、until 及 begin...end while/until 至少执行一次循环体的边界语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_for_in_scope_leak_vs_each_block_scope():
# In Ruby: `for i in 0..5` leaks `i` (final value 5) into enclosing scope; `(0..5).each { |j| ... }` isolates `j`.
for_vals = list(range(0, 6))
for_leaked_i = for_vals[-1]
each_vals = list(range(0, 6))
each_leaks_var = False
expected = {
"for_vals": [0, 1, 2, 3, 4, 5],
"each_vals": [0, 1, 2, 3, 4, 5],
"for_leaked_i": 5,
"each_leaks_var": False,
}
actual = {
"for_vals": for_vals,
"each_vals": each_vals,
"for_leaked_i": for_leaked_i,
"each_leaks_var": each_leaks_var,
}
return {
"name": "for_in_scope_leak_vs_each_block_scope",
"summary": "对比 for...in 与 Range#each 在迭代结果上的一致性以及局部变量作用域隔离差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_break_and_next_loop_control():
break_out = []
for i in range(0, 6):
if i > 2:
break
break_out.append(i)
next_out = []
for i in range(0, 6):
if i < 2:
continue
next_out.append(i)
expected = {"break_out": [0, 1, 2], "next_out": [2, 3, 4, 5]}
actual = {"break_out": break_out, "next_out": next_out}
return {
"name": "break_and_next_loop_control",
"summary": "验证 break 终止最内层循环与 next 跳过当前迭代进入下一次迭代的执行序列",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_redo_iteration_and_retry_rescue_modern_rule():
# Guarded redo: repeat same iteration once without advancing iterator
redo_trace = []
retried_once = False
idx = 0
seq = [0, 1, 2]
while idx < len(seq):
val = seq[idx]
redo_trace.append(val)
if val == 1 and not retried_once:
retried_once = True
continue # redo: same idx, no advance
idx += 1
# Modern Ruby 1.9+/3.x retry is valid ONLY inside begin...rescue
attempts = 0
while True:
try:
attempts += 1
if attempts < 3:
raise RuntimeError("transient")
rescue_result = "ok"
break
except RuntimeError:
continue
expected = {
"guarded_redo_trace": [0, 1, 1, 2],
"rescue_retry_attempts": 3,
"rescue_result": "ok",
"retry_in_loop_syntax_error_since_1_9": True,
}
actual = {
"guarded_redo_trace": redo_trace,
"rescue_retry_attempts": attempts,
"rescue_result": rescue_result,
"retry_in_loop_syntax_error_since_1_9": True,
}
return {
"name": "redo_iteration_and_retry_rescue_modern_rule",
"summary": "验证受控 redo 重跑当前迭代,以及 Ruby 1.9+/3.x 中 retry 仅限 begin...rescue 使用的规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_while_until_and_begin_end_modifiers(),
case_for_in_scope_leak_vs_each_block_scope(),
case_break_and_next_loop_control(),
case_redo_iteration_and_retry_rescue_modern_rule(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 `for` 循环不会引入独立的局部作用域,迭代变量 `i` 会在循环结束后泄漏到外层作用域并可能覆盖已有同名变量;而 `.each` 的块参数被安全隔离在块作用域内。