Ruby 迭代器
介绍 Ruby 集合(Array 与 Hash)的核心迭代机制,重点区分 each 副作用遍历与 collect(map)元素映射变换的语法、返回值及与 clone 复制的差异。
学完这一章,你能够
- 介绍 Ruby 集合(Array 与 Hash)的核心迭代机制,重点区分 each 副作用遍历与 collect(map)元素映射变换的语法、返回值及与 clone 复制的差异。
集合与 Ruby each 迭代器
在 Ruby 中,迭代指重复按序处理一组元素,而迭代器(Iterator)是集合对象原生提供的方法。能够保存多个数据成员的对象(最典型的是 `Array` 和 `Hash`)统称为集合,通过调用集合上的迭代器并传入代码块即可逐一消费元素,无需手写下标循环。
`each` 是最常用的遍历迭代器,基本语法为 `collection.each do |variable| ... end`。调用 `ary = [1, 2, 3, 4, 5]` 的 `ary.each` 时,Ruby 会依次将每个元素绑定到块参数 `i` 并执行块内逻辑(例如逐行打印 1 到 5)。`each` 注重执行副作用,调用完毕后返回原集合对象本身,而非块内表达式的返回值;在现代 Ruby 中若省略代码块,`each` 会返回一个 `Enumerator` 对象以便链式组合。
Ruby collect(map)映射迭代器与 clone 区分
`collect`(别名 `map`)则面向“逐项变换并收集新数组”的场景:它对集合中的每个元素执行代码块,并将每次块计算的返回值按顺序装入一个全新的 `Array` 返回。需注意两点现代 Ruby 3.x 语义:第一,在 Ruby 1.9+ 中不带块调用 `a.collect` 返回的是 `Enumerator`(需 `.to_a` 才会转为数组),并非直接返回原集合副本;第二,若目标仅仅是浅拷贝一个数组,应使用 `a.clone` 或 `a.dup`,而不是写 `a.collect { |x| x }`。
`collect` 真正的优势在于无副作用地生成派生数据。例如对 `a = [1, 2, 3, 4, 5]` 执行 `b = a.collect { |x| 10 * x }`,将得到新数组 `[10, 20, 30, 40, 50]`,同时保持原数组 `a` 内容不变;日常开发中还可与 `select`、`reject` 等其他 `Enumerable` 迭代器组合构成清晰的数据流水线。
离线校验 Ruby each 遍历返回值、collect/map 映射变换与 clone 复制差异
"""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()
- 3 个确定性用例全部通过,确认 Array/Hash each 行为、collect 生成新数组且不改原数组,以及 clone 独立浅拷贝。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
当前源码 SHA256:d06f33c6148b4cdd51636d353a4d4a6768f48915bc54907bd8febc5610d680f4
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
ZIP SHA256:7d79130eb827e402ff57024c480f7f0af895dd8b6077591ee8925ac6f7804038
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
什么时候该用 `each`,什么时候该用 `collect`(或 `map`)?
展开参考解答
仅需对元素执行打印、写日志等副作用且不关心收集新结果时用 `each`;需要将原集合逐项映射转换为新数组时用 `collect`/`map`。