From: Mark Sparshatt Date: 2004-07-18T07:43:53+09:00 Subject: Re: [NUBY] Ruby Way code for shuffling an array doesn't behave as expected 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? > > > This is due to changes in Ruby between v1.6.8 and 1.8 It's because the block passed to collect is changing the contents of a, so it doesn't reach all the elements of a. Changing the line to puts a.dup.collect {a.slice!(rand(a.length)) }.inspect fixes it HTH -- Mark Sparshatt