Entries Tagged as 'arrays'

Friday, October 6th, 2006

Randomizing an array in Ruby

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
  [...]