这里有几个inject() 的实际应用示例:
[1, 2, 3, 4].inject(0) {|memo, num| memo += num; memo} # sums all elements in array
该示例遍历 [1, 2, 3, 4] 数组的每个元素,并将元素添加到 memo 变量(memo 通常用作块变量名称)。此示例在每次迭代后显式返回 memo,但返回也可以是隐式的。
[1, 2, 3, 4].inject(0) {|memo, num| memo += num} # also works
inject() 在概念上类似于以下显式代码:
result = 0
[1, 2, 3, 4].each {|num| result += num}
result # result is now 10
inject() 对于创建数组和散列也很有用。下面是如何使用inject() 将[['dogs', 4], ['cats', 3], ['dogs', 7]] 转换为{'dogs' => 11, 'cats' => 3}。
[['dogs', 4], ['cats', 3], ['dogs', 7]].inject({'dogs' => 0, 'cats' => 0}) do |memo, (animal, num)|
memo[animal] = num
memo
end
这是一个更通用、更优雅的解决方案:
[['dogs', 4], ['cats', 3], ['dogs', 7]].inject(Hash.new(0)) do |memo, (animal, num)|
memo[animal] = num
memo
end
同样,inject() 在概念上类似于以下代码:
result = Hash.new(0)
[['dogs', 4], ['cats', 3], ['dogs', 7]].each do |animal, num|
result[animal] = num
end
result # now equals {'dogs' => 11, 'cats' => 3}