Array#reverse
Added in v1.8 · Updated March 14, 2026 · Array Methods
ruby array reverse
.reverse returns a new array with elements in reverse order. .reverse! reverses the array in place.
Brief Intro
reverse creates a new array with elements in reverse order. reverse! modifies the original array. Both are useful when you need to process elements backward, display data in reverse order, or implement algorithms that work from the end toward the beginning.
Signature
| Method | Parameters | Return Type |
|---|---|---|
reverse | none | Array |
reverse! | none | Array (self) |
Code Examples
Basic Reverse
array = [1, 2, 3, 4, 5]
array.reverse
# => [5, 4, 3, 2, 1]
array
# => [1, 2, 3, 4, 5] (original unchanged)
In-Place Reverse with reverse!
array = [1, 2, 3, 4, 5]
array.reverse!
# => [5, 4, 3, 2, 1]
array
# => [5, 4, 3, 2, 1] (original modified)
Reversing Strings in an Array
words = ["apple", "banana", "cherry"]
words.reverse
# => ["cherry", "banana", "apple"]
Practical Use: Processing Last Items First
tasks = ["design", "code", "test", "deploy"]
# Process tasks in reverse order
tasks.reverse.each do |task|
puts "Cleaning up: #{task}"
end
# Output:
# Cleaning up: deploy
# Cleaning up: test
# Cleaning up: code
# Cleaning up: design
Using with Other Array Methods
numbers = [1, 2, 3, 4, 5]
# Get last 3 elements, reversed
numbers.last(3).reverse
# => [5, 4, 3]
# Reverse after sorting
numbers.sort.reverse
# => [5, 4, 3, 2, 1]
# Reverse each element (for arrays of strings)
["dog", "cat", "bird"].map(&:reverse)
# => ["god", "tac", "drib"]
Building a Stack-Based Processing Pipeline
history = ["page1", "page2", "page3", "page4"]
# Navigate back through history
history.reverse.each do |page|
puts "Caching: #{page}"
end
# Output:
# Caching: page4
# Caching: page3
# Caching: page2
# Caching: page1
Reversing Multi-Dimensional Arrays
matrix = [[1, 2], [3, 4], [5, 6]]
# Reverse the rows
matrix.reverse
# => [[5, 6], [3, 4], [1, 2]]
# Reverse each row
matrix.map(&:reverse)
# => [[2, 1], [4, 3], [6, 5]]
# Both: reverse rows then reverse each row
matrix.reverse.map(&:reverse)
# => [[6, 5], [4, 3], [2, 1]]
Return Value
reversereturns a new array with elements in reverse order. The original array remains unchanged.reverse!returns self (the modified array), allowing method chaining.
Edge Cases
- Empty array returns a new empty array.
[].reverse
# => []
[].reverse!
# => []
- Single-element array returns itself (new array for
reverse, same object forreverse!).
[42].reverse
# => [42]
[42].reverse!
# => [42]