问题描述
我发现 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 的命名方法
因此,指定一个符号相当于传递以下块:返回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(&:+)"如何?在 Ruby 中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!