Why doesn't Array # each_with_object (0) work?

Why using 0as argument to each_with_objectdoes not return the correct value:

[1,2,3].each_with_object(0) {|i,o| o += i }
# => 0

but using an empty array and reduce(:+)does?

[1,2,3].each_with_object([]) {|i,o| o << i }.reduce(:+)                               
# => 6
+4
source share
2 answers

The documentation says:

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.

Since Array is the same source object, but with changed values, is returned in this case.

If we see the code of each_with_object, this is:

# 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 0 , , [] , .

+3

Ruby, , .

0 . ( [] ) . , , .

+3

All Articles