views:

683

answers:

5

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

+11  A: 

Built in now:

 [1,2,3,4].shuffle => [2, 1, 3, 4]
 [1,2,3,4].shuffle => [1, 3, 2, 4]
Ron Gejman
And if you want to implement it yourself: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
Joey
Or if you want it for Ruby < 1.9:require 'backports'
Marc-André Lafortune
Looks like it's in Ruby 1.8.7 too.
Brian Armstrong
+6  A: 

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

array.sort_by { rand }
sepp2k
A: 

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'...

edavey
+4  A: 

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

bry4n
A: 

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
Vizjerai