Sorting By Functions in Crystal
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 Crystal.
In this Crystal version:
We don’t need to import any modules as Crystal’s standard library is available by default.
Instead of
slices.SortFunc
, we use Crystal’s built-insort_by!
method which sorts the array in-place.The comparison function is simplified to use Crystal’s spaceship operator
<=>
.For sorting custom types, we define a
Person
class instead of a struct. Crystal uses classes for this kind of structure.We use Crystal’s property syntax to automatically create getter and setter methods for
name
andage
.We implement a
to_s
method forPerson
to make the output more readable.The sorting of
people
is done using the samesort_by!
method, specifying theage
property to sort by.
When you run this program, you should see output similar to:
This example demonstrates how to perform custom sorting in Crystal, both for built-in types and custom classes.