Enumerable 是一个模块,提供了一套丰富的方法来遍历、搜索和操作集合 — map、select、reduce、find、 等等。数组、哈希表、范围,以及任何定义了 的类都会获得所有这些方法。它是 Ruby 优雅、函数式数据处理的核心。
group_byeach[1, 2, 3, 4, 5]
.select { |n| n.even? } # filter → [2, 4]
.map { |n| n * 10 } # transform → [20, 40]
[1, 2, 3, 4].reduce(0) { |sum, n| sum + n } # 10 — fold/accumulate (also .sum)
[1, 2, 3, 4].find { |n| n > 2 } # 3 — first match
[1, 2, 3, 4].all? { |n| n > 0 } # true
[1, 2, 3, 4].any? { |n| n > 3 } # true
[1, 2, 3, 4].count { |n| n.even? } # 2
[3, 1, 2].sort; [3, 1, 2].min; [3, 1, 2].max
[1, 2, 3].each_with_index { |val, i| ... }
words.group_by { |w| w.length } # group into a hash by a key
[1, 2, 3, 4].partition { |n| n.even? } # [[2,4], [1,3]] — split by condition
[1, 2, 3].each_slice(2).to_a # [[1,2],[3]] — chunks
Enumerable 提供了数十个表达力强的方法用于过滤、转换、聚合、搜索、分组和分块 — 覆盖几乎所有集合操作,可链式调用以创建简洁的数据管道。
{ a: 1, b: 2 }.select { |k, v| v > 1 } # hashes are Enumerable → { b: 2 }
(1..100).map { |n| n * 2 } # ranges are Enumerable
class TodoList
include Enumerable # mix in Enumerable...
def initialize = @items = []
def each(&block) # ...just define `each`...
@items.each(&block)
end
# ...and you get map, select, reduce, find, sort, etc. FOR FREE!
end
list = TodoList.new
list.select { |item| item.done? } # works! — Enumerable provides it via your `each`
优雅之处在于:include Enumerable 并仅定义 each,你的类就会自动获得 所有 Enumerable 的方法(map、select、reduce 等)。
Enumerable 模块是 Ruby 优雅、表达力强的数据处理风格的核心,理解它对于高效、习惯用法的 Ruby 开发至关重要。
它提供了丰富、全面的方法集合(map、select、reduce、find、group_by、partition、all?、any? 等等)来处理集合 — 而这些你在数组、哈希表和范围上不断使用的方法,正是使 Ruby 的数据操作如此简洁易读的原因(链式调用表达力强的操作,而不是编写冗长的循环)。
掌握 Enumerable 的方法是编写流畅、函数式风格 Ruby 代码的关键 — 这就是你优雅地过滤、转换、聚合、搜索和分组数据的方式。
除了在内置集合上使用这些方法外,一个重要的、具有 Ruby 特色的特性是你可以让 你自己的类变成 Enumerable:通过 include Enumerable 并仅定义 each 方法,你的类会自动获得 所有 Enumerable 的方法(map、select、reduce 等)— 这是 Ruby mixin 设计的强大演示,也是构建表现得像数组的自定义集合类的实用工具。
理解 Enumerable — 它丰富的方法(Ruby 表达式数据处理的基础)、数组/哈希表/范围都包含它、以及如何通过定义 each 让自定义类成为 Enumerable — 这些都是重要的、频繁应用的知识,是编写习惯用法的 Ruby 代码的核心。
由于 Enumerable 方法的数据处理在 Ruby(和 Rails)中无处不在,而且 include Enumerable + each 模式是 Ruby mixin 能力的优雅示例,掌握 Enumerable 是有效、习惯用法的 Ruby 开发的基础,也是反映对该语言表达式集合处理能力掌握程度的常见话题。