Ruby Program to Reverse Array with Example and Explanation
reverse method like this: reversed_array = array.reverse.Examples
How to Think About It
reverse that does this for you without needing to manually swap elements.Algorithm
Code
array = [1, 2, 3, 4, 5] reversed_array = array.reverse puts reversed_array.inspect
Dry Run
Let's trace the array [1, 2, 3, 4, 5] through the code
Original array
array = [1, 2, 3, 4, 5]
Reverse the array
reversed_array = array.reverse # reversed_array = [5, 4, 3, 2, 1]
Print the reversed array
puts reversed_array.inspect # outputs [5, 4, 3, 2, 1]
| Step | Array State |
|---|---|
| Initial | [1, 2, 3, 4, 5] |
| After reverse | [5, 4, 3, 2, 1] |
Why This Works
Step 1: Using the reverse method
The reverse method returns a new array with elements in the opposite order without changing the original array.
Step 2: Storing the reversed array
We save the reversed array in a new variable to keep the original array intact.
Step 3: Printing the result
Using puts with inspect shows the array in a readable format.
Alternative Approaches
array = [1, 2, 3, 4, 5] array.reverse! puts array.inspect
array = [1, 2, 3, 4, 5] left = 0 right = array.length - 1 while left < right array[left], array[right] = array[right], array[left] left += 1 right -= 1 end puts array.inspect
Complexity: O(n) time, O(n) space
Time Complexity
The reverse method processes each element once, so it takes linear time proportional to the array size.
Space Complexity
It creates a new array to hold the reversed elements, so it uses extra space proportional to the array size.
Which Approach is Fastest?
Using reverse! is faster in space because it reverses in place, but reverse is safer when you want to keep the original array unchanged.
| Approach | Time | Space | Best For |
|---|---|---|---|
| reverse | O(n) | O(n) | When you want a reversed copy without changing original |
| reverse! | O(n) | O(1) | When you want to reverse the array in place to save memory |
| Manual swapping | O(n) | O(1) | Learning how reversal works internally or custom logic |
reverse for a simple way to get a reversed copy of an array without modifying the original.reverse returns a new array and does not change the original.