为什么在 each_with_object
中使用 0
作为参数没有返回正确的值:
[1,2,3].each_with_object(0) {|i,o| o += i }
# => 0
但是使用空数组和 reduce(:+)
可以吗?
[1,2,3].each_with_object([]) {|i,o| o << i }.reduce(:+)
# => 6
最佳答案
来自 documentation它说:
each_with_object(obj) → an_enumerator
Iterates the given block for each element with an arbitrary object given, and returns the initially given object.
If no block is given, returns an enumerator.
由于 Array 是相同的初始对象,但在这种情况下返回修改后的值。
如果我们看到 code each_with_object 的,是:
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 79
def each_with_object(memo)
return to_enum :each_with_object, memo unless block_given?
each do |element|
yield element, memo
end
memo
end
你可以看到,它不修改 memo,所以如果 memo 是 0
而你在代码块中改变它,它仍然会返回零,但如果你通过 []
并在代码块中更改它,它将返回具有值的数组。
关于ruby - 为什么 Array#each_with_object(0) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29210335/