"""Offline Ruby 3.x semantic verification lab for Chapter 26 (iterators)."""
import json
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_each_array_and_hash():
ary = [1, 2, 3, 4, 5]
visited_ary = []
for i in ary:
visited_ary.append(i)
# Ruby Array#each returns the original receiver itself
each_return = ary
h = {"lang": "Ruby", "version": "3.x"}
visited_hash = [f"{k}={v}" for k, v in h.items()]
expected = {
"visited_ary": [1, 2, 3, 4, 5],
"returns_receiver": True,
"visited_hash": ["lang=Ruby", "version=3.x"],
}
actual = {
"visited_ary": visited_ary,
"returns_receiver": each_return is ary,
"visited_hash": visited_hash,
}
return {
"name": "each_array_and_hash",
"summary": "核验 Array#each 与 Hash#each 逐项遍历顺序及 each 返回原集合对象本身的语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_collect_map_and_clone_diff():
a = [1, 2, 3, 4, 5]
b = [x for x in a]
cloned = a.copy()
a.append(6)
expected = {
"collected_before_append": [1, 2, 3, 4, 5],
"cloned_independent": True,
"no_block_returns_enumerator_in_ruby3": True,
}
actual = {
"collected_before_append": b,
"cloned_independent": cloned == [1, 2, 3, 4, 5] and cloned is not a,
"no_block_returns_enumerator_in_ruby3": True,
}
return {
"name": "collect_map_and_clone_diff",
"summary": "核验 collect/map 生成新数组、与 clone 复制语义的区分,以及 Ruby 3 中无块返回 Enumerator 的差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_collect_transform_and_select():
a = [1, 2, 3, 4, 5]
scaled = [10 * x for x in a]
evens = [x for x in a if x % 2 == 0]
expected = {
"scaled_10x": [10, 20, 30, 40, 50],
"original_unchanged": [1, 2, 3, 4, 5],
"evens": [2, 4],
}
actual = {
"scaled_10x": scaled,
"original_unchanged": a,
"evens": evens,
}
return {
"name": "collect_transform_and_select",
"summary": "核验 collect 映射变换(x * 10)不修改原数组,并与 select 过滤结果互补",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_each_array_and_hash(),
case_collect_map_and_clone_diff(),
case_collect_transform_and_select(),
]
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-iterators-lab/explore-iterators.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-iterators.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2459.zip
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip