OneBite.Dev - Coding blog in a bite size

shuffle the elements in an array in Ruby

Code snippet on how to shuffle the elements in an array in Ruby

  array = [3,5,2,4,1] 
  array.shuffle!

  shuffled_array = []
  array.each do |item|
    shuffled_array << item
  end

This code begins by creating an array called array with five elements. It then shuffles the elements of the array in place using the built-in shuffle! method. It then creates an empty array called shuffled_array. A loop is then used to iterate through the original array and add each element to the shuffled_array. Finally, the shuffled_array is returned and will contain all the elements from the original array in a random order.

ruby