蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 while/until 修饰符、for 与 each 作用域差异、break/next 及受控 redo/rescue retry

PYTHONWindows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。explore-loop.py
explore-loop.py150 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。

入口文件:projects/ruby-loop-lab/explore-loop.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-loop.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Ruby

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2461.zip

下载课程关联工程包:Ruby

课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习