Shuffle That Array

A quick yet interesting tidbit about .shuffle vs. .shuffle!

.shuffle will return a new array with the elements of the original array shuffled. The original array won’t change unless you reassign it to a variable.

a = [1, 2, 3, 4, 5]
a.shuffle
=> [3, 4, 1, 5, 2]
a
=> [1, 2, 3, 4, 5]

.shuffle! will return the original array with its elements rearranged. This does change the original array.

a = [1, 2, 3, 4, 5]
a.shuffle!
=> [4, 2, 5, 3, 1]
a
=> [4, 2, 5, 3, 1]

I stumbled on this when writing a command line game of Blackjack (you can find it here). Every time I would start up the game, I would be dealt the same two cards. When I’d hit, I’d get the same third card, and fourth card as well. The array was being shuffled, but in the exact same way every time. That’s because computer “randomness” isn’t very random — it was shuffling the same exact array with the same algorithm every time, which was causing me to get the same results and play a very boring game. By changing the original array, the cards would get shuffled in a different way almost every time which is more like a real life game. Always remember user experience and your app will be in a good place.

I have like, three blackjacks in this hand. I win, human.
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.