Hi --

On Fri, 2 Dec 2005, Hammed Malik wrote:

> I'd like to sort collections randomly. This is what I tried first:
>
> my_array.sort { |a,b| rand(2) }
>>
>
> but the results weren't very random. I then tried the following:
>
> class Array
>>   def random_copy
>>     b = Array.new
>>     while b.length < self.length
>>       random_value = self[rand self.length]
>>       b.push random_value unless b.include? random_value
>>     end
>>     b
>>   end
>> end
>
>
>
> This works but I'm sure there's some Ruby magic for doing this better.

I think the most common idiom is:

   array.sort_by { rand }


David

-- 
David A. Black
dblack / wobblini.net

"Ruby for Rails", forthcoming from Manning Publications, April 2006!