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
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
Built in now:
[1,2,3,4].shuffle => [2, 1, 3, 4]
[1,2,3,4].shuffle => [1, 3, 2, 4]
For ruby 1.8.6 (which does not have shuffle built in):
array.sort_by { rand }
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'...
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
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