skip to comments

Shuffling an Array in Ruby

UPDATE Someone called NoKarma and perraultd have posted even nicer versions on the Code Snippets site, thanks!:

class Array
  def shuffle
    sort_by { rand }
  end
 
  def shuffle!
    self.replace shuffle
  end
end

I had a situation when I need to shuffle the contents of an array to randomize the stuff inside. After hunting and hacking the final solution appeared to be:

class Array
  def shuffle!
    size.downto(1) { |n| push delete_at(rand(n)) }
    self
  end
end

So you just enhance the Array Class and give it a new funky method shuffle! so you can do stuff like:

a = [1,2,3,4,5,6,7,8,9]
a.shuffle!
=> [5, 2, 8, 7, 3, 1, 6, 4, 9]

Just how cool is Ruby.

Go ahead, have your say ..

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">


back to the top