This content originally appeared on DEV Community and was authored by Glenn Tippett
Ruby has a bunch of useful built-in methods for manipulating Arrays; here we are looking at the Shuffle method which takes an array and returns a new array with the order of elements shuffled.
Nice, done!
But what if we wanted to shuffle an array without this built-in method?
You know… because why not?
There are a few examples of this, such as the Fisher-Yates Shuffle, but what really needs to happen underneath the hood?
If I have 10 different coloured Lego blocks in a certain order which I want to randomise I could put them all into a box, shake the box, then pick out a random piece one at a time.
I wouldn’t then put those pieces back into the same box, I would put them in a new box (one that could keep them in a new order) so I don’t pick the same Lego block twice.
I would continue this until my original box is empty.
How could this look in Ruby?
Here is our Lego example in Ruby.
An array is passed into the method, which is then duplicated so we’re not editing the original array – you could say we’re putting our Lego blocks into its first box.
We then initialise an empty array – this is our empty box to put the Lego blocks into.
One by one we close our eyes and choose a random index from the array, give the value from the index to the empty box (array_b) and delete it from the original array.
Notice we choose a random number between 0 and the original array length then save that number to its own variable. We then use that variable when pushing to array_b and deleting from array_a rather than generating another random number each time.
After deleting that index from array_a the length becomes 1 less so there are fewer options to choose a random number from on the next iteration.
Eventually, our original box is empty and the new box holds the same values in a randomised order, which is then returned on the last line of the method.
There are quite a few ways you could approach this problem including just using the built-in shuffle method, but now we know its secrets…
This content originally appeared on DEV Community and was authored by Glenn Tippett
Glenn Tippett | Sciencx (2021-03-22T04:18:40+00:00) Ruby Shuffle Method. Retrieved from https://www.scien.cx/2021/03/22/ruby-shuffle-method/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.

