0
0
Rubyprogramming~5 mins

Array sorting and reversing in Ruby

Choose your learning style9 modes available
Introduction

Sorting and reversing arrays help organize data so it's easier to find or use. Sorting arranges items in order, and reversing flips their order.

When you want to list names alphabetically.
When you need to show numbers from smallest to largest or largest to smallest.
When you want to reverse the order of items, like showing the latest messages first.
When preparing data for reports that require sorted or reversed lists.
Syntax
Ruby
class Array
  # Sorts the array in ascending order and returns a new array
  def sorted_array
    self.sort
  end

  # Reverses the array and returns a new array
  def reversed_array
    self.reverse
  end
end

The sort method returns a new array sorted in ascending order.

The reverse method returns a new array with elements in reverse order.

Examples
This sorts numbers from smallest to largest.
Ruby
numbers = [3, 1, 4, 2]
sorted_numbers = numbers.sort
puts sorted_numbers.inspect
This sorts words alphabetically.
Ruby
words = ["banana", "apple", "cherry"]
sorted_words = words.sort
puts sorted_words.inspect
Reversing an empty array returns an empty array.
Ruby
empty_array = []
reversed_empty = empty_array.reverse
puts reversed_empty.inspect
Reversing an array with one element returns the same array.
Ruby
single_element = [42]
reversed_single = single_element.reverse
puts reversed_single.inspect
Sample Program

This program shows the original array, then the sorted version, and finally the reversed version.

Ruby
numbers = [5, 2, 9, 1, 7]
puts "Original array: #{numbers.inspect}"

sorted_numbers = numbers.sort
puts "Sorted array: #{sorted_numbers.inspect}"

reversed_numbers = numbers.reverse
puts "Reversed array: #{reversed_numbers.inspect}"
OutputSuccess
Important Notes

Sorting an array usually takes time proportional to the number of elements times the logarithm of that number (O(n log n)).

Reversing an array takes time proportional to the number of elements (O(n)).

A common mistake is to expect sort or reverse to change the original array. They return new arrays instead.

Use sort! or reverse! if you want to change the original array.

Summary

Sorting arranges array elements in order, usually ascending.

Reversing flips the order of elements in the array.

Both methods return new arrays unless you use the versions with ! to modify in place.