Quantcast
Channel: Whomwah.com » howto
Viewing all articles
Browse latest Browse all 9

Shuffling an Array in Ruby

$
0
0

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


Viewing all articles
Browse latest Browse all 9

Trending Articles