Sorting in Ruby

Ruby’s standard library includes sorting capabilities for arrays. We’ll look at sorting for built-in types first.

# Sorting functions work for any array of elements that can be compared.

# Sort an array of strings
strs = ["c", "a", "b"]
strs.sort!
puts "Strings: #{strs}"

# An example of sorting integers
ints = [7, 2, 4]
ints.sort!
puts "Ints:    #{ints}"

# We can also check if an array is already in sorted order.
s = ints == ints.sort
puts "Sorted:  #{s}"

To run the program, save it as sorting.rb and use the ruby command:

$ ruby sorting.rb
Strings: ["a", "b", "c"]
Ints:    [2, 4, 7]
Sorted:  true

In Ruby, the sort! method modifies the original array in place. If you want to create a new sorted array without modifying the original, you can use the sort method instead.

Ruby’s sorting is based on the comparison operator (<=>) of the elements. For built-in types like strings and numbers, this works out of the box. For custom objects, you would need to define the comparison operator or provide a custom sorting block.

The sort and sort! methods in Ruby are equivalent to the slices.Sort function in the original example. Ruby’s built-in sorting is highly optimized and works efficiently for most use cases.

To check if an array is sorted, we compare it with its sorted version. This is a simple way to achieve the same functionality as the slices.IsSorted function in the original example.