Member-only story
Ruby’s Comparable Module & Combined Comparison Operator
Using the Spaceship Operator for Three-Way Comparison 👽
Using Ruby’s Comparable Module & Combined Comparison Operator, aka The Spaceship Operator
How can we use Ruby’s Comparable Module?
Comparable Module adds comparison operators to our classes. It’s mixed into Numeric and String classes, and not inherited. We can add it to our custom classes like so:
The Comparable mixin is used by classes whose objects may be ordered. The class must define the <=> operator, which compares the receiver against another object, returning -1, 0, or +1 depending on whether the receiver is less than, equal to, or greater than the other object. If the other object is not comparable then the <=> operator should return nil. Comparable uses <=> to implement the conventional comparison operators (<, <=, ==, >=, and >)…








