DEV Community

loading...

Shuffle Array in Ruby

rrtutors profile image rrtutors Originally published at rrtutors.com ・1 min read

How to shuffle an array in Ruby?

write a function that shuffle!() array of elements random
Multiple runs of shuffle may lead to different orders of elements. For instance


shuffle!() is a Array class method which shuffles elements in an array


Syntax

Array.shuffle!()
Enter fullscreen mode Exit fullscreen mode



Example


a = [1, 22, 123, nil, 2, 3]

# declaring array

b = [12, 24, 41, 1, 48, 99]

# declaring array

c = [18, 22, 50, 6]

# shuffle! method example

puts "shuffle!() method form : #{a.shuffle!()}\n\n"

puts "shuffle!() method form : #{b.shuffle!()}\n\n"

puts "shuffle!() method form : #{c.shuffle!()}\n\n"

Enter fullscreen mode Exit fullscreen mode



Output


shuffle!() method form : [2, 1, 123, 3, nil, 22]

shuffle!() method form : [24, 99, 48, 1, 12, 41]

shuffle!() method form : [50, 18, 6, 22]
Enter fullscreen mode Exit fullscreen mode



Read Add elements to array in ruby

Discussion (0)

pic
Editor guide