From: Jason Creighton Date: 2003-07-08T11:02:09+09:00 Subject: Re: Code Snippet: Array.shuffle On 08 Jul 2003 03:01:30 +0200 Stefan Arentz wrote: > > Here is another small Ruby code snippet that extends the Array class. Use > this to randomize the order of all entries in an Array. > > class Array > def shuffle > self.each_index { |i| r = rand(self.length - 1); > self[i],self[r] = self[r],self[i] } > end > end > > Works like this: > > a = Array[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > a.shuffle > ==> [7, 10, 9, 6, 4, 8, 5, 3, 1, 2] >> ary = (0..10).to_a => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >> ary.sort { rand(3)-1 } => [4, 6, 5, 0, 2, 3, 9, 7, 8, 1, 10] .....of course, this probably won't produce as random as result, but it's easier to implement. Jason Creighton