From: Bug Free on
The following line:

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

prints [5, 7] but I'm expecting [[5, 0], [7, 1]].

Does anyone know how/why this is happening ?

thanks
--
Posted via http://www.ruby-forum.com/.

From: Caleb Clausen on
On 5/30/10, Bug Free <amberarrow(a)yahoo.com> wrote:
> The following line:
>
> [5, 7].each_with_index.each_cons(2) {|v| p v }
>
> prints [5, 7] but I'm expecting [[5, 0], [7, 1]].
>
> Does anyone know how/why this is happening ?

Works for me in 1.9.3. Maybe a 1.9.1 bug?

From: botp on
On Mon, May 31, 2010 at 9:04 AM, Bug Free <amberarrow(a)yahoo.com> wrote:
> The following line:
>
>    [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,

>> [5, 7].map.with_index{|v,i| [v,i]}
=> [[5, 0], [7, 1]]

kind regards -botp

From: Robert Klemme on
2010/5/31 botp <botpena(a)gmail.com>:
> On Mon, May 31, 2010 at 9:04 AM, Bug Free <amberarrow(a)yahoo.com> wrote:
>> The following line:
>>
>>    [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,
>
>>>  [5, 7].map.with_index{|v,i| [v,i]}
> => [[5, 0], [7, 1]]

That's not the proper replacement with map. Rather you'd do:

irb(main):009:0> [5, 7].each_with_index.map {|v| v }
=> [5, 7]
irb(main):010:0> [5, 7].each_with_index.map {|*v| v }
=> [[5, 0], [7, 1]]

Interestingly the splat operator does not include the index with #each_cons:

irb(main):011:0> [5, 7].each_with_index.each_cons(2) {|v| p v }
[5, 7]
=> nil
irb(main):012:0> [5, 7].each_with_index.each_cons(2) {|*v| p v }
[[5, 7]]
=> nil

This is on ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-cygwin].

I'd say it's a bug which seems to be reflected by the fact that it
works as expected in 1.9.3 according to Caleb.

Cheers

robert

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

From: Robert Dober on
On Mon, May 31, 2010 at 10:34 AM, Robert Klemme
<shortcutter(a)googlemail.com> wrote:
> I'd say it's a bug which seems to be reflected by the fact that it
> works as expected in 1.9.3 according to Caleb.
Even more so, as
[5, 7].each_with_index.to_a.each_cons(2) {|v| p v }
[[5, 0], [7, 1]]

Seems quite straight forward to me that the to_a should not change the
semantics.
R.