How to randomly sort (scramble) an array in Ruby?

Daniel Cukier picture Daniel Cukier · Nov 29, 2009 · Viewed 69.6k times · Source

I'd like to have my array items scrambled. Something like this:

[1,2,3,4].scramble => [2,1,3,4]
[1,2,3,4].scramble => [3,1,2,4]
[1,2,3,4].scramble => [4,2,3,1]

and so on, randomly

Answer

Ron Gejman picture Ron Gejman · Nov 29, 2009

Built in now:

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