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







2 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
Leave a Reply