Ruby Array Randomize

Ruby Array Randomize

by blamoreaux 15. August 2007 09:09

I needed the ability to randomize the order of an array. This is useful when you have a set collection of questions in a survey that you want to shuffle before you present them to the user. After looking around a bit, I didn't find anything that worked. Here is what I pieced together with my limited knowledge of Ruby. 

# Created by Brig R. Lamoreaux
# Date: 11 July 2007
# Time: 10:38 am
 
# Randomize the contents of an Array
class Array
  def randomize
    a=self.dup
    result = []
    self.length.times do
      result << a.slice!(rand(a.length))
    end
    return result
  end
  def randomize!
    a=self.dup
    result = []
    self.length.times do
      result << a.slice!(rand(a.length))
    end
    self.replace result
  end
end

Here are some test that make sure it really works.

puts "Randomize Tests"
x = [1, 2, 3, 4, 5]
print "x: "
x.each do |i|
  print "#{i}"
end
 
y = x.randomize
print "\ny: "
y.each do |i|
  print "#{i}"
end
 
x.randomize! # x is now [3, 5, 4, 1, 2]
print "\nx: "
x.each do |i|
  print "#{i}"
end
 
x.randomize! # x is now [3, 5, 4, 1, 2]
print "\nx: "
x.each do |i|
  print "#{i}"
end

Special thanks to syntaxhighlighter on providing styles for ruby syntax highlighting.

Update: After doing a search for array shuffle, I found some useful examples.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

November 20. 2008 00:15

Gravatar

Powered by BlogEngine.NET 1.1.0.7
Theme by Mads Kristensen

Subscribe

About the author

Brig Lamoraeux Brig Lamoreaux
I'm a .Net developer.

E-mail me Send mail

Calendar

<<  November 2008  >>
MoTuWeThFrSaSu
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar

Pages

Recent posts

Recent comments

Tags

Categories


Archive

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2006-2008

Sign in