Shuffle an array in Ruby
A quick look at the ‘shuffle’, ‘rand’ and ‘sample’ array methods in Ruby.
I needed to randomly sort the elements in a Ruby on Rails array for a project I’m working on. Turns out these things are just way too easy in Ruby:
Credits to Tom Klaasen to improve the more complex snippet I had earlier.
There is also a ‘rand’ method when you only need a single element and don’t need to shuffle the whole array in Ruby 1.8.
Or in Ruby 1.9.