Enum#each issue

Ok! I tried the below:

2.0.0p0 :001 > a = [1,2,3,4]
=> [1, 2, 3, 4]
2.0.0p0 :002 > m=a.to_enum(:map!)
=> #<Enumerator: [1, 2, 3, 4]:map!>
2.0.0p0 :003 > m.next
=> 1
2.0.0p0 :004 > a
=> [1, 2, 3, 4]

Still ok.

2.0.0p0 :005 > m.next
=> 2
2.0.0p0 :006 > a
=> [nil, 2, 3, 4]

Now how that nil comes above? I am totally confused.

2.0.0p0 :007 > m.next
=> 3
2.0.0p0 :008 > a
=> [nil, nil, 3, 4]
2.0.0p0 :009 >

read about what map! does, and why the return of a block (or in this
case the #feed) is important

because the block is similar to a e.feed(function(e.next))

and you do not call the feed, without ruby does not know wich value it
should set for the element

Hans M. wrote in post #1109744:

read about what map! does, and why the return of a block (or in this
case the #feed) is important

Yes! I read it - Invokes the given block once for each element of
self, replacing the element with the value returned by the block.
why
block returns nil where as a.next returns value from the enum,for
each next call? <~~ That’s the pain.

Thanks

Hans M. wrote in post #1109748:

because the block is similar to a e.feed(function(e.next))

and you do not call the feed, without ruby does not know wich value it
should set for the element

Okay! understood.

enum#feed says - “Sets the value to be returned by the next yield inside
e.” Now in my below example, why the feeded value comes after the second
next call?

def meth
[1,2,3].each {|e| p yield(e)}
end
=> nil

?> m = to_enum(:meth)
=> #<Enumerator: main:meth>

m.feed “foo”
=> nil

m.next
=> 1

?> ^C

m.next
“foo”
=> 2

Hans M. wrote in post #1109757:

its because how it works …

first you need to call next
then you call feed to set the value,
and then the next call of next does apply the change (even if it raise
an StopIteration error

Thanks for all your helps. Understood. Tricky method it is.

its because how it works …

first you need to call next
then you call feed to set the value,
and then the next call of next does apply the change (even if it raise
an StopIteration error