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

Leave a Reply