Ruby - Sort an Array

1. Introduction

Sorting is a fundamental operation in computer science and is often required in various programming tasks. Ruby offers built-in methods to sort arrays in both ascending and descending order. In this tutorial, we will demonstrate how to sort an array in Ruby.

2. Program Steps

1. Define or initialize an array.

2. Use the sort method to sort the array in ascending order.

3. Use the sort { |a, b| b <=> a } method to sort the array in descending order.

4. Print the sorted arrays to the console.

3. Code Program

# Define an unsorted array
numbers = [65, 25, 30, 10, 50, 45]
# Sort the array in ascending order
sorted_ascending = numbers.sort
# Sort the array in descending order
sorted_descending = numbers.sort { |a, b| b <=> a }
# Print the sorted arrays
puts "Original Array: #{numbers}"
puts "Sorted in Ascending Order: #{sorted_ascending}"
puts "Sorted in Descending Order: #{sorted_descending}"

Output:

Original Array: [65, 25, 30, 10, 50, 45]
Sorted in Ascending Order: [10, 25, 30, 45, 50, 65]
Sorted in Descending Order: [65, 50, 45, 30, 25, 10]

Explanation:

1. numbers = [65, 25, 30, 10, 50, 45]: We initialize an unsorted array named numbers.

2. numbers.sort: The built-in sort method sorts the array in ascending order by default.

3. numbers.sort { |a, b| b <=> a }: This syntax sorts the array in descending order. The <=> is known as the spaceship operator, which returns -1 if a is less than b, 0 if they're equal, and 1 if a is greater than b. By flipping a and b in the block, we achieve descending order.

4. The sorted arrays are printed to the console.

The built-in sort method in Ruby provides a quick and efficient way to order the elements of an array.


Comments