How to Rotate an Array in Ruby: Simple Syntax and Examples
In Ruby, you can rotate an array using the
rotate method, which shifts elements by a specified number of positions. For example, array.rotate(2) moves the first two elements to the end. If no number is given, it rotates by one position by default.Syntax
The rotate method is called on an array and takes an optional integer argument that specifies how many positions to rotate the array.
array.rotate(n): Rotates the array left bynpositions.- If
nis positive, elements are moved from the front to the back. - If
nis negative, elements are moved from the back to the front. - If no argument is given, it defaults to
1.
ruby
array.rotate(n = 1)Example
This example shows how to rotate an array by different numbers of positions using rotate. It demonstrates positive, negative, and default rotation.
ruby
arr = [10, 20, 30, 40, 50] puts "Original array: #{arr}" rotated_by_2 = arr.rotate(2) puts "Rotate by 2: #{rotated_by_2}" rotated_by_minus_1 = arr.rotate(-1) puts "Rotate by -1: #{rotated_by_minus_1}" rotated_default = arr.rotate puts "Rotate by default (1): #{rotated_default}"
Output
Original array: [10, 20, 30, 40, 50]
Rotate by 2: [30, 40, 50, 10, 20]
Rotate by -1: [50, 10, 20, 30, 40]
Rotate by default (1): [20, 30, 40, 50, 10]
Common Pitfalls
One common mistake is expecting rotate to modify the original array. It actually returns a new rotated array and leaves the original unchanged.
To change the original array, use rotate! which modifies the array in place.
ruby
arr = [1, 2, 3, 4] rotated = arr.rotate(1) puts "Original after rotate: #{arr}" puts "Returned rotated array: #{rotated}" arr.rotate!(1) puts "Original after rotate!: #{arr}"
Output
Original after rotate: [1, 2, 3, 4]
Returned rotated array: [2, 3, 4, 1]
Original after rotate!: [2, 3, 4, 1]
Quick Reference
| Method | Description | Modifies Original? |
|---|---|---|
| rotate(n) | Returns a new array rotated left by n positions (default 1) | No |
| rotate!(n) | Rotates the array in place by n positions | Yes |
Key Takeaways
Use
array.rotate(n) to get a new array rotated by n positions without changing the original.Use
array.rotate! to rotate the array in place and modify the original array.Positive n rotates left; negative n rotates right.
If no argument is given,
rotate defaults to rotating by 1 position.Remember
rotate returns a new array, so assign it if you want to keep the rotated version.