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.
Let’s break down the differences and similarities:
In Ruby, we don’t need to import any libraries for this basic functionality.
Instead of
slices.SortFunc
, we use Ruby’s built-insort!
method with a custom comparison block.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.For sorting custom objects, we use
sort_by!
which is a more idiomatic way in Ruby to sort by a specific attribute.We define a
Person
struct usingStruct.new
which is similar to thePerson
struct in the original example.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:
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.