On Fri, 30 Jan 2009, Bart Braem wrote:

> Perhaps a silly question. What is the best way to add a randomize
> method to array? I know that this code will properly randomize an
> array:
>
> a.sort_by{ rand }
>
> but I wonder how I can know add this to the array class. I can't
> assign self to the result of this method, so this will not work:
>
> class Array
>  def randomize
>    self = self.sort_by{ rand }
>  end
> end
>
> What is the best way to do this?

I have no idea how performant this is compared to other ways but the
first thing that occurs to me is:

   class Array
     def randomize
       replace(sort_by { rand })
     end
   end

Ruby 1.9 has shuffle and shuffle! methods to shuffle arrays (the ! one
being an in-place version).


David

-- 
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2)

http://www.wishsight.com => Independent, social wishlist management!