需要对inject方法的简单说明 [英] Need a simple explanation of the inject method

查看:56
本文介绍了需要对inject方法的简单说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

我正在查看这段代码,但我的大脑并没有记录数字 10 如何成为结果.有人介意解释一下这里发生了什么吗?

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

推荐答案

您可以将第一个块参数视为累加器:块每次运行的结果都存储在累加器中,然后传递给下一次执行块.在上面显示的代码的情况下,您将累加器结果默认为 0.块的每次运行都会将给定的数字添加到当前总数中,然后将结果存储回累加器.下一个块调用具有这个新值,添加到它,再次存储它,然后重复.

You can think of the first block argument as an accumulator: the result of each run of the block is stored in the accumulator and then passed to the next execution of the block. In the case of the code shown above, you are defaulting the accumulator, result, to 0. Each run of the block adds the given number to the current total and then stores the result back into the accumulator. The next block call has this new value, adds to it, stores it again, and repeats.

在过程结束时,inject 返回累加器,在这种情况下,它是数组中所有值的总和,或 10.

At the end of the process, inject returns the accumulator, which in this case is the sum of all the values in the array, or 10.

这是从对象数组创建哈希的另一个简单示例,以它们的字符串表示为键:

Here's another simple example to create a hash from an array of objects, keyed by their string representation:

[1,"a",Object.new,:hi].inject({}) do |hash, item|
  hash[item.to_s] = item
  hash
end

在这种情况下,我们将累加器默认为空哈希,然后在每次块执行时填充它.请注意,我们必须将哈希作为块的最后一行返回,因为块的结果将存储回累加器中.

In this case, we are defaulting our accumulator to an empty hash, then populating it each time the block executes. Notice we must return the hash as the last line of the block, because the result of the block will be stored back in the accumulator.

这篇关于需要对inject方法的简单说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆