Ruby - Reverse an Array

1. Introduction

Reversing elements in an array is a common operation in programming tasks. Ruby offers built-in methods to easily reverse the order of elements in an array. In this post, we'll explore how to reverse an array in Ruby.

2. Program Steps

1. Define or initialize an array.

2. Use the reverse method to get the reversed array.

3. Print the original and reversed arrays to the console.

3. Code Program

# Define an array
numbers = [1, 2, 3, 4, 5]
# Reverse the array
reversed_numbers = numbers.reverse
# Print the original and reversed arrays
puts "Original Array: #{numbers}"
puts "Reversed Array: #{reversed_numbers}"

Output:

Original Array: [1, 2, 3, 4, 5]
Reversed Array: [5, 4, 3, 2, 1]

Explanation:

1. numbers = [1, 2, 3, 4, 5]: We initialize an array named numbers.

2. numbers.reverse: The built-in reverse method returns a new array containing the elements in reverse order.

3. We then print both the original and the reversed arrays to the console.

The reverse method provides an effortless way to obtain a reversed version of an array in Ruby without altering the original array.


Comments