Add randomize method to array?


#1

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?


#2

On Thu, Jan 29, 2009 at 1:57 PM, David A. Black removed_email_address@domain.invalid
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!


#3

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 (http://manning.com/black2)

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


#4

2009/1/29 David A. Black removed_email_address@domain.invalid:

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!"

http://de.wikipedia.org/wiki/Hexeneinmaleins

Cheers

robert


#5

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

On Thu, Jan 29, 2009 at 1:57 PM, David A. Black removed_email_address@domain.invalid 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 (http://manning.com/black2)

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