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.
Array sorting and reversing in 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.
numbers = [3, 1, 4, 2] sorted_numbers = numbers.sort puts sorted_numbers.inspect
words = ["banana", "apple", "cherry"] sorted_words = words.sort puts sorted_words.inspect
empty_array = []
reversed_empty = empty_array.reverse
puts reversed_empty.inspectsingle_element = [42] reversed_single = single_element.reverse puts reversed_single.inspect
This program shows the original array, then the sorted version, and finally the reversed version.
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}"
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.
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.