How to shuffle an array in Ruby

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.

Syntax

array.shuffle()
# OPTIONAL range argument
array.shuffle(random: range)

Parameters

Optionally, the shuffle() can take a range parameter which is then used as the random number generator.

Return value

The shuffle() method returns a new array with elements of the original array shuffled.

Example

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 instances
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Javascript", "Python", "Java", "C++", "Ruby"]
array4 = ["cat", "dog", "elephant", "whale"]
# shuffle arrays
a = array1.shuffle()
b = array2.shuffle()
c = array3.shuffle()
d = array4.shuffle()
# print results
puts "#{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 array
array = [1, 2, 3, 4, 5]
# pass optional range value
shuffledArray = array.shuffle(random: Random.new(2))
# print shuffled array
puts "#{shuffledArray}"
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources