In Ruby, you can shuffle an array using the built-in shuffle
method, which implements the Fisher-Yates shuffle algorithm.
In this example,
int_array
containing integers.shuffle
method to shuffle int_array
.int_array = [1, 2, 3, 4, 5]
shuffled_array = int_array.shuffle
puts 'Shuffled Array:', shuffled_array.join(' ')
Shuffled Array: 4 1 2 5 3
In this example,
str_array
containing strings.shuffle
method to shuffle str_array
.str_array = ['apple', 'banana', 'cherry']
shuffled_array = str_array.shuffle
puts 'Shuffled Array:', shuffled_array.join(' ')
Shuffled Array: banana apple cherry
In this tutorial, we learned How to Shuffle an Array in Ruby language with well detailed examples.