The shuffle()
function shuffles arrays in Ruby. It returns a new array with elements of the original array shuffled. Like some array functions in Ruby, the shuffle()
function does not modify the original array when called on it.
array.shuffle()
# OPTIONAL range argument
array.shuffle(random: range)
Optionally, the shuffle()
can take a range
parameter which is then used as the random number generator.
The shuffle()
method returns a new array with elements of the original array shuffled.
The example below demonstrates the use of the shuffle()
method in Ruby. Several arrays with elements are created, and the shuffle method is called on them. Then, the returned values are printed to the console.
# create array instancesarray1 = [1, 2, 3, 4, 5]array2 = ["a", "b", "c", "d", "e"]array3 = ["Javascript", "Python", "Java", "C++", "Ruby"]array4 = ["cat", "dog", "elephant", "whale"]# shuffle arraysa = array1.shuffle()b = array2.shuffle()c = array3.shuffle()d = array4.shuffle()# print resultsputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"
When we pass the optional range parameter, the value will be used as the random number generator. See the example below:
# create an arrayarray = [1, 2, 3, 4, 5]# pass optional range valueshuffledArray = array.shuffle(random: Random.new(2))# print shuffled arrayputs "#{shuffledArray}"