2010/5/31 botp <botpena / gmail.com>:
> On Mon, May 31, 2010 at 4:34 PM, Robert Klemme
>> 2010/5/31 botp <botpena / gmail.com>:
>>> On Mon, May 31, 2010 at 9:04 AM, Bug Free <amberarrow / yahoo.com> wrote:
>>>> The following line:
>>>>
>>>> =A0 =A0[5, 7].each_with_index.each_cons(2) {|v| p v }
>>>>
>>>> prints [5, 7] but I'm expecting [[5, 0], [7, 1]].
>>>
>>> you'll have specify the index, eg,
>>>
>>>>> =A0[5, 7].map.with_index{|v,i| [v,i]}
>>> =3D> [[5, 0], [7, 1]]
>>
>> That's not the proper replacement with map. =A0Rather you'd do:
>>
>> irb(main):009:0> [5, 7].each_with_index.map {|v| v }
>> =3D> [5, 7]
>> irb(main):010:0> [5, 7].each_with_index.map {|*v| v }
>> =3D> [[5, 0], [7, 1]]
>
> can you enlighten me on what is "not proper" ? =A0:)
>
> ie why is each_with_index.map preferable over map.with_index ?

Because it is closer on what OP initially did:

[5, 7].each_with_index.each_cons(2) {|v| p v }

The sequence "[5, 7].each_with_index" returns an Enumerator which must
yield a value and an index on each iteration:

irb(main):001:0> [5, 7].each_with_index.each {|*a| p a}
[5, 0]
[7, 1]
=3D> [5, 7]

On this Enumerator which #each_cons is invoked.

Contrast that to your suggestion "[5, 7].map.with_index{|v,i| [v,i]}":
here "[5, 7].map" returns an Enumerator which must yield values *only*
- the index is added by "#map_with_index".

irb(main):002:0> [5, 7].map.each {|*a| p a}
[5]
[7]
=3D> [[5], [7]]

This means that in your code the index cannot get lost along the way
simply because it is added in the last step and not in the initial
step.  Hope it's clearer now.

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/