Published by Simon Schoeters

Shuffle an array in Ruby

I needed to randomly sort the elements in an array in the Ruby on Rails 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 for improving the more complex snippet I found before.

Or you can use the rand method when you only need one single element and don't need to shuffle the whole array in Ruby 1.8:

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

And for Ruby 1.9:

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