ruby array randomly display
To randomly display elements from an array in Ruby, you can use the shuffle
method. Here is an example:
array = [1, 2, 3, 4, 5]
shuffled_array = array.shuffle
puts shuffled_array
Explanation:
- We start by defining an array called
array
with the numbers 1 to 5. - We then use the
shuffle
method on thearray
to randomly rearrange its elements. Theshuffle
method returns a new array with the elements in a random order. - Finally, we use
puts
to display the shuffled array on the console.
This code will output a random arrangement of the elements in the array. Each time you run the code, the order of the elements will be different.