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:

[1, 2, 3].shuffle
>> [3, 1, 2]

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.

[1, 2, 3].rand
>> 3

Or in Ruby 1.9.

[1, 2, 3].sample
>> 3