To rotate elements in an array using Ruby, you can use the built-in methods like `rotate` or implement a custom rotation function.
In this example,
int_array
containing integers.rotate
method to rotate the array by a specified number of positions.int_array = [1, 2, 3, 4, 5]
positions = 2
rotated_array = int_array.rotate(positions)
puts "Rotated Array: #{rotated_array}"
Rotated Array: [3, 4, 5, 1, 2]
In this example,
str_array
containing strings.rotate
method to rotate the array by a specified number of positions.str_array = ["apple", "banana", "cherry", "date", "fig"]
positions = 3
rotated_array = str_array.rotate(positions)
puts "Rotated Array: #{rotated_array}"
Rotated Array: ["date", "fig", "apple", "banana", "cherry"]
In this tutorial, we learned How to Rotate Elements in an Array in Ruby language with well detailed examples.