Topic: Randomizing Positions in an Array

I'm trying to randomize an array, and this is what I have:

arr_set_unordered = randomizer(arr_set)

  def randomizer(arr)
   result = arr.collect { arr.slice!(rand arr.length) }

It does randomize it, but it only returns 3 values instead of the 5 that should get returned (arr_set is an  Any ideas why?

Thank you!

Last edited by jwcooper (2006-12-22 05:50:59)

Re: Randomizing Positions in an Array

I think it has to do with the array being shortened in the middle of being looped through.  I was about to write up some solution to this when I realize there's a much, much better version here:
It's a modification to array that lets you do:
and you'd get a random list.

pretty snazzy.

Re: Randomizing Positions in an Array

There's also:

arr.sort { rand }

For a quick solution.

Railscasts - Free Ruby on Rails Screencasts

Re: Randomizing Positions in an Array

Thank you, I ended up doing:

arr.sort_by { rand }

Not sure what the difference is between mine and ryanb's answer though.

Thank you!