From: Brian Candler Date: 2003-07-08T15:33:58+09:00 Subject: Re: Code Snippet: Array.shuffle On Tue, Jul 08, 2003 at 10:21:42AM +0900, 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 rand(x) gives a number between 0 and x-1, so I think you should use rand(self.length) not rand(self.length-1). In particular this will work properly for arrays containing 1 element. You could also replace self.each_index and self.length with each_index and length, respectively. And you don't need the semicolon. Regards, Brian.