Add randomize method to array?

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?

On Thu, Jan 29, 2009 at 1:57 PM, David A. Black [email protected]
wrote:

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

Ruby 1.8.7 also have shuffle and shuffle!

On Fri, 30 Jan 2009, Bart B. wrote:

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 (The Well-Grounded Rubyist)

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

2009/1/29 David A. Black [email protected]:

I consider 1.8.7 to be 1.9.-1 :slight_smile:
Uh, oh this is spooooky… Reminds me of:

This must thou ken:
Of one make ten,
Pass two, and then
Make square the three,
So rich thou’lt be.
Drop out the four!
From five and six,
Thus says the witch,
Make seven and eight.
So all is straight!
And nine is one,
And ten is none,
This is the witch’s one-time-one!

Original

„Du mußt versteh’n!
Aus Eins mach Zehn,
Und Zwei laß geh’n,
Und Drei mach gleich,
So bist Du reich.
Verlier die Vier!
Aus Fünf und Sechs,
So sagt die Hex’,
Mach Sieben und Acht,
So ist’s vollbracht:
Und Neun ist Eins,
Und Zehn ist keins.
Das ist das Hexen-Einmaleins!"

Cheers

robert

On Fri, 30 Jan 2009, Luis P. wrote:

On Thu, Jan 29, 2009 at 1:57 PM, David A. Black [email protected] wrote:

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

Ruby 1.8.7 also have shuffle and shuffle!

I consider 1.8.7 to be 1.9.-1 :slight_smile:

David


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

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