To reverse an array in Ruby, you can do the following:
Using Array#reverse
You can use the Array#reverse
method to return a new array with the elements in reverse order:
arr = [1, 2, 3, 4, 5] reversed_arr = arr.reverse print reversed_arr #=> [5, 4, 3, 2, 1]
If you wish to modify the original array in place, then you can use the Array#reverse!
method instead:
arr = [1, 2, 3, 4, 5] arr.reverse! print arr #=> [5, 4, 3, 2, 1]
Using a Loop
You can reverse an array using a loop by creating two pointers that swap elements at the opposite ends of the array until you reach the middle. The loop continues until the left pointer crosses the right pointer, at which point the array would be fully reversed. For example, this can be implemented in the following way:
def reverse_array(arr) left_pointer = 0 right_pointer = arr.length - 1 # loop till the pointers reach the middle while left_pointer < right_pointer # swap elements at opposite ends arr[left_pointer], arr[right_pointer] = arr[right_pointer], arr[left_pointer] # increment counters left_pointer += 1 right_pointer -= 1 end arr end arr = [1, 2, 3, 4, 5] reversed_arr = reverse_array(arr) print reversed_arr #=> [5, 4, 3, 2, 1]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.