Skip to main content

Ruby shuffle array method

In ruby programming language, shuffle() array methods are return a new array which contains random shuffle elements of applied array. Syntax of this method as follows.

shuffle → new array
shuffle() → new array

shuffle() array method example

Resultant array of this method contains n elements. Here n is the number of element in apply array. Let's see an example.

# Our array
arr  = [3, 2, 5, 6]

# shuffle operation
s1 = arr.shuffle
s2 = arr.shuffle()

# Display result
print(" s1 : ",s1)
print("\n s2 : ",s2)
Ruby shuffle method example 1
 s1 : [3, 5, 6, 2]
 s2 : [3, 2, 6, 5]

When array is empty then this method is return a new empty array. And array elements contains objects and other class collection. such this case object is referenced by new array elements.

# Our array
a1  = [[1,2],[true,nil],10]
a2  = []
# shuffle operation
s1 = a1.shuffle
s2 = a1.shuffle
s3 = a2.shuffle
# Display result
print(" s1 : ",s1)
print("\n s2 : ",s2)
print("\n s3 : ",s3)
Ruby shuffle method example 2
 s1 : [[true, nil], 10, [1, 2]]
 s2 : [[1, 2], 10, [true, nil]]
 s3 : []


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment