It’s often desirable to compare two or more objects for some sort of custom sort order. Ruby implements this by default in many classes using the comparison (<=>) operator. This comparison operator is used internally whenever you call the sort method to impose some kind of order on an array of strings, integers, or anything else. Comparing two arbitrary objects directly using the comparison operator will return -1, 0, or 1 depending on if the calling object is less than, equal to, or greater than the object it’s being compared to.
If you have a unique class that needs comparison behavior (or alternatively you want to override the default comparison behavior in some existing class), it’s as easy as including the Ruby Comparable mixin. If you’re familiar with the Java Comparable interface, then this is very similar.
After including the Comparable mixin, simply define a <=> method that implements the comparison behavior you’re looking for. In this case, I always want my “boss” sorted to the top of the list in any comparison. Otherwise, just perform a default comparison between titles of the two Person objects. That would be a string comparison in this scenario, meaning an alphabetical sort.
Defining the <=> method will also give you all of the default comparison operators (<, <=, ==, >=, and >), as well as the between? method.
It should be noted that it’s generally a good idea to have your comparison return nil in the event that it can’t be compared to the other object.