Sorting By Functions in Ruby

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Ruby.

# We don't need to import any libraries for this example in Ruby

# Define our main function
def main
  fruits = ["peach", "banana", "kiwi"]

  # We implement a comparison function for string lengths
  len_cmp = ->(a, b) { a.length <=> b.length }

  # Now we can call sort with this custom comparison function to sort fruits by name length
  fruits.sort!(&len_cmp)
  puts fruits.inspect

  # We can use the same technique to sort an array of custom objects
  Person = Struct.new(:name, :age)

  people = [
    Person.new("Jax", 37),
    Person.new("TJ", 25),
    Person.new("Alex", 72)
  ]

  # Sort people by age
  people.sort_by!(&:age)
  puts people.inspect
end

# Call the main function
main

Let’s break down the differences and similarities:

  1. In Ruby, we don’t need to import any libraries for this basic functionality.

  2. Instead of slices.SortFunc, we use Ruby’s built-in sort! method with a custom comparison block.

  3. The comparison function in Ruby uses the spaceship operator <=> which returns -1, 0, or 1 based on whether the left operand is less than, equal to, or greater than the right operand.

  4. For sorting custom objects, we use sort_by! which is a more idiomatic way in Ruby to sort by a specific attribute.

  5. We define a Person struct using Struct.new which is similar to the Person struct in the original example.

  6. The main function in Ruby is just a regular method, not a special function like in some other languages.

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

$ ruby sorting_by_functions.rb
["kiwi", "peach", "banana"]
[#<struct Person name="TJ", age=25>, #<struct Person name="Jax", age=37>, #<struct Person name="Alex", age=72>]

This example demonstrates how to perform custom sorting in Ruby, both for built-in types and custom objects. Ruby’s blocks and the sort_by! method provide a concise and readable way to implement custom sorting logic.