“(1..4).inject(&:+)"如何?在 Ruby 中工作 [英] How does "(1..4).inject(&:+)" work in Ruby

查看:38
本文介绍了“(1..4).inject(&:+)"如何?在 Ruby 中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Ruby 中的这段代码非常有趣

I find this code in Ruby to be pretty intriguing

(1..4).inject(&:+)

好的,我知道inject做了什么,而且我知道这段代码基本上等价于

Ok, I know what inject does, and I know this code is basically equivalent to

(1..4).inject(0) {|a,n| a + n}

但它究竟是如何工作的?

but how exactly does it work?

为什么 &:+ 和写块 {|a,n| 是一样的a + n}?

为什么不需要初始值?我对初始值为 0 没问题,但是 (1..4).inject(&:*) 也可以,并且初始值必须是 1...

Why it doesn't need an initial value? I'm ok with the inicial value being 0, but (1..4).inject(&:*) also works, and there the initial value must be 1...

推荐答案

来自 Ruby 文档:

如果你指定了一个符号,那么集合中的每个元素都会被传递给 memo 的命名方法

If you specify a symbol instead, then each element in the collection will be passed to the named method of memo

因此,指定一个符号相当于传递以下块:<代码>{|备忘录,一个|memo.send(sym, a)}

So, specifying a symbol is equivalent to passing the following block: {|memo, a| memo.send(sym, a)}

如果没有明确指定memo的初始值,那么使用集合的第一个元素作为memo的初始值.

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

所以,没有什么魔法,Ruby 只是将第一个元素作为初始值,然后从第二个元素开始注入.您可以通过编写 [].inject(:+) 来检查它:它返回 nil 而不是 [].inject(0, :+)返回0.

So, there is no magic, Ruby simply takes the first element as the initial value and starts injecting from the second element. You can check it by writing [].inject(:+): it returns nil as opposed to [].inject(0, :+) which returns 0.

我没有注意到&符号.你不需要它,inject 将使用一个符号.但是如果你写了它,符号被转换为块,它可以用于 其他方法

I didn't notice the ampersand. You don't need it, inject will work with a symbol. But if you do write it, the symbol is converted to block, it can be useful with other methods

这篇关于“(1..4).inject(&amp;:+)"如何?在 Ruby 中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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