Friday, October 6th, 2006...11:49 pm
Randomizing an array in Ruby
Jump to Comments
Ruby's Array class has no method to randomize the contents of an array. Of course, Array can easily be extended to include this functionality. And like anything else in Ruby, there's more than one way to do it. Here's one way:
class Array
def randomize
arr=self.dup
self.collect { arr.slice!(rand(arr.length)) }
end
def randomize!
self.replace self.randomize
end
def random
self.randomize.first
end
end







3 Comments
December 28th, 2006 at 5:58 am
Thankyou this is working well for me!
July 4th, 2007 at 5:55 am
Much simpler:
class Array
def randomize
self.sort_by { rand }
end
def randomize!
self.replace(randomize)
end
end
September 1st, 2010 at 8:42 am
the articles on this publish is really 1 of the most effective substance that We have at any time are available throughout. I really like your publish, I will appear again to examine for new posts.
Leave a Reply