On Jul 17, 2004, at 3:12 PM, Alexey Verkhovsky wrote:

> One example in The Ruby Way claims that in the following snippet second
> line shuffles the a (i.e., makes an array consisting of the same
> elements as a, but in a different order).
>
> a = [1, 2, 3, 4, 5]
> puts a.collect { a.slice!(rand(a.length)) }.inspect
>
> The claim sounds reasonable, but in reality Ruby 1.9 (CVS HEAD) always
> returns an array of three random elements, not of five as expected.
>
> Why is that so?

It appears that #each is being affected by the slicing of the array 
that it is acting on. By the time it gets to the third element, it's 
the last one. So it stops.

It doesn't seem to do that in 1.6.x; I assume #each worked on a copy of 
the array back then...

RUBY_VERSION
     ==>"1.6.8"
a=[1,2,3,4,5]
     ==>[1, 2, 3, 4, 5]
p a.collect{a.slice!(rand(a.length))}
[4, 3, 5, 2, 1]
     ==>nil

To fix it in later versions, use a.dup.collect instead. That should fix 
the odd behavior.

HTH,
Mark