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

RubyArraysRandomShuffle

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

Built in now:

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

Solution 2 - Ruby

For ruby 1.8.6 (which does not have shuffle built in):

array.sort_by { rand }

Solution 3 - Ruby

For ruby 1.8.6 as sepp2k's example, but you still want use "shuffle" method.

class Array
  def shuffle
    sort_by { rand }
  end
end

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

cheers

Solution 4 - Ruby

Code from the Backports Gem for just the Array for Ruby 1.8.6. Ruby 1.8.7 or higher is built in.

class Array
  # Standard in Ruby 1.8.7+. See official documentation[http://ruby-doc.org/core-1.9/classes/Array.html]
  def shuffle
    dup.shuffle!
  end unless method_defined? :shuffle

  # Standard in Ruby 1.8.7+. See official documentation[http://ruby-doc.org/core-1.9/classes/Array.html]
  def shuffle!
    size.times do |i|
      r = i + Kernel.rand(size - i)
      self[i], self[r] = self[r], self[i]
    end
    self
  end unless method_defined? :shuffle!
end

Solution 5 - Ruby

The Ruby Facets library of extensions has a Random module which provides useful methods including shuffle and shuffle! to a bunch of core classes including Array, Hash and String.

Just be careful if you're using Rails as I experienced some nasty clashes in the way its monkeypatching clashed with Rails'...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel CukierView Question on Stackoverflow
Solution 1 - RubyRon GejmanView Answer on Stackoverflow
Solution 2 - Rubysepp2kView Answer on Stackoverflow
Solution 3 - Rubybry4nView Answer on Stackoverflow
Solution 4 - RubyVizjeraiView Answer on Stackoverflow
Solution 5 - RubyedaveyView Answer on Stackoverflow