shuffle an array in ruby

To shuffle an array in Ruby, you can use the shuffle method, which is a built-in method of the Array class. Here's an example:

main.rb
my_array = [1, 2, 3, 4, 5]
shuffled_array = my_array.shuffle
puts shuffled_array.inspect
89 chars
4 lines

This will output an shuffled version of the array my_array.

Alternatively, you can shuffle an array in place using the shuffle! method:

main.rb
my_array.shuffle!
puts my_array.inspect
40 chars
3 lines

This will modify the original array my_array and shuffle its elements randomly.

Another way is to use the sort_by method with a random number generator:

main.rb
my_array.sort_by { rand }
26 chars
2 lines

This will return a shuffled version of the array my_array. Note that this method doesn't modify the original array, it returns a new shuffled array.

related categories

gistlibby LogSnag