I\'m trying to figure out how each_with_object
is supposed to be used.
I have a sum example that doesn\'t work:
> (1..3).each_with_ob
The documentation of Enumerable#each_with_object is very clear :
Iterates the given block for each element with an arbitrary object given, and returns the initially given object.
In your case, (1..3).each_with_object(0) {|i,sum| sum+=i}
,you are passing 0
,which is immutable object. Thus here the intial object to each_with_object
method is 0
,so method returns 0
.It works at it is advertised. See below how each_with_object
works ,
(1..3).each_with_object(0) do |e,mem|
p "#{mem} and #{e} before change"
mem = mem + e
p mem
end
# >> "0 and 1 before change"
# >> 1
# >> "0 and 2 before change"
# >> 2
# >> "0 and 3 before change"
# >> 3
That means in every pass,mem
is set to initial passed object. You might be thinking of the in first pass mem
is 0
,then in next pass mem
is the result of mem+=e
,i.e. mem
will be 1
.But NO,in every pass mem
is your initial object,which is 0
.