Add randomize method to array?

B

Bart Braem

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?
 
D

David A. Black

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

Robert Klemme

2009/1/29 David A. Black said:
I consider 1.8.7 to be 1.9.-1 :)

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

=84Du mu=DFt versteh'n!
Aus Eins mach Zehn,
Und Zwei la=DF geh'n,
Und Drei mach gleich,
So bist Du reich.
Verlier die Vier!
Aus F=FCnf 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

--=20
remember.guy do |as, often| as.you_can - without end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top