Rotate An Array By N Positions In Ruby
Shift array elements left or right by N positions using Array#rotate.
Description
Array#rotate returns a new array with elements rotated left by N positions (negative N rotates right). It is the idiomatic way to implement round-robin scheduling, circular buffers, or any algorithm that needs cyclic access to an ordered list. The original array is not modified.
Sample input:
arr = [1, 2, 3, 4, 5]
Sample Output:
[3, 4, 5, 1, 2] # rotated left by 2
Answer
arr = [1, 2, 3, 4, 5]
# Rotate left by 2 (default is 1)
arr.rotate(2)
# => [3, 4, 5, 1, 2]
# Rotate right by 1 (negative argument)
arr.rotate(-1)
# => [5, 1, 2, 3, 4]
# Rotate in place
arr.rotate!(2)
arr # => [3, 4, 5, 1, 2]
# Round-robin: always pick the first element, then rotate
queue = ["Alice", "Bob", "Carol"]
current = queue.first
queue = queue.rotate(1)
# next call: current = "Bob", queue rotates again
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀