[ruby-core:63373] Re: Unexpected behaviour of cycle and zip

From: Marc-Andre Lafortune <ruby-core-mailing-list@...>
Date: 2014-06-27 16:41:42 UTC
List: ruby-core #63373
Hi

> Is it wrong to expect the enumerator to behave as a cycle starting from i=
ts current position for operations like zip and take?

Your confusion is understandable, but this is not how the enumerators
were designed. At the end of the doc for `next` you'll find:

    Note that enumeration sequence by next does not affect other
non-external enumeration methods, unless the underlying iteration
methods itself has side-effect, e.g. IO#each_line

I think this design choice is in part because using `next` is much
slower then `each`.

Hope this helps.

On Fri, Jun 27, 2014 at 3:16 AM, Jes=C3=BAs Gabriel y Gal=C3=A1n
<jgabrielygalan@gmail.com> wrote:
> Hi,
>
> (I already posted this in Ruby Talk, and it was suggested to check in Cor=
e)
>
> I was surprised today with a behaviour, maybe my expectation was wrong
> and someone can explain why it works this way:
>
> I have an array of elements, and I want to cycle through it assigning
> each element to another list of elements. But the cycle can be already
> in the middle. For example:
>
> a =3D [1,2,3]
>
> b =3D [6,7,8,9,10]
>
> the desired result should be (if the next element in the cycle was 2):
>
> [[6,2], [7,3], [8,1],[9,2],[10,3]]
>
> So I, intuitively tried this:
>
> 2.0.0-p195 :469 > b =3D [6,7,8,9,10]
>  =3D> [6, 7, 8, 9, 10]
> 2.0.0-p195 :471 > a =3D [1,2,3].cycle
>  =3D> #<Enumerator: [1, 2, 3]:cycle>
> 2.0.0-p195 :472 > a.next
>  =3D> 1
> 2.0.0-p195 :473 > a.peek
>  =3D> 2
> 2.0.0-p195 :474 > b.zip(a)
>  =3D> [[6, 1], [7, 2], [8, 3], [9, 1], [10, 2]]
>
> So, it seems that the enumerator a is starting from the beginning,
> instead of from the "next". If I read correctly the source code (MRI)
> it seems that zip uses take, and testing this shows that it always
> starts from the beginning:
>
> 2.0.0-p195 :475 > a.take 2
>  =3D> [1, 2]
> 2.0.0-p195 :476 > a.take 2
>  =3D> [1, 2]
> 2.0.0-p195 :477 > a.take 2
>  =3D> [1, 2]
>
> Is it wrong to expect the enumerator to behave as a cycle starting
> from its current position for operations like zip and take?
>
> Thanks,
>
> Jesus.

In This Thread