0
0
RubyHow-ToBeginner · 3 min read

How to Reverse an Array in Ruby: Simple Syntax and Examples

In Ruby, you can reverse an array using the reverse method which returns a new array with elements in reverse order. To reverse the array in place, use reverse! which modifies the original array.
📐

Syntax

The reverse method returns a new array with the elements reversed, leaving the original array unchanged. The reverse! method reverses the elements of the array in place, changing the original array.

ruby
array.reverse
array.reverse!
💻

Example

This example shows how to use reverse to get a reversed copy of the array and reverse! to reverse the array itself.

ruby
array = [1, 2, 3, 4, 5]

reversed_array = array.reverse
puts "Reversed copy: #{reversed_array.inspect}"
puts "Original array after reverse: #{array.inspect}"

array.reverse!
puts "Original array after reverse!: #{array.inspect}"
Output
Reversed copy: [5, 4, 3, 2, 1] Original array after reverse: [1, 2, 3, 4, 5] Original array after reverse!: [5, 4, 3, 2, 1]
⚠️

Common Pitfalls

A common mistake is expecting reverse to change the original array. It only returns a new reversed array. To modify the original array, you must use reverse!. Forgetting the exclamation mark means the original array stays the same.

ruby
array = [10, 20, 30]

# Wrong: This does not change the original array
array.reverse
puts array.inspect  # Output: [10, 20, 30]

# Right: This changes the original array
array.reverse!
puts array.inspect  # Output: [30, 20, 10]
Output
[10, 20, 30] [30, 20, 10]
📊

Quick Reference

  • array.reverse: Returns a new reversed array, original unchanged.
  • array.reverse!: Reverses the array in place, modifying the original.

Key Takeaways

Use reverse to get a reversed copy without changing the original array.
Use reverse! to reverse the array itself and modify it.
Remember reverse does not change the original array, only returns a new one.
For in-place reversal, always use reverse! with the exclamation mark.
Check your array after reversal to confirm if it was changed or not.