Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 134 ยท Collections

Comparable

Learn Ruby's Comparable module - define the spaceship operator <=> once and get <, >, ==, between? and clamp, sort and min/max custom objects, handle nil results and compare safely.

Numbers, strings, times and versions can all be put in order, and Ruby lets you ask the same questions of all of them: is a smaller than b, is it between two limits, which of these is the largest? For your own classes, you teach Ruby how to order two objects by writing one method, the spaceship operator <=>, and then you add include Comparable. The module builds <, <=, >, >=, ==, between? and clamp out of it.

This is the companion of Enumerable: Enumerable gives a collection its methods from each, and Comparable gives a single object its comparison methods from <=>. Together they make sort, min, max and minmax work on your own classes.

The spaceship operator

a <=> b returns a number telling you how the two relate: -1 when a comes first, 0 when they are equal, 1 when a comes later, and nil when they cannot be compared at all.

Ruby What <=> returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Only the sign matters for sorting and comparing, so code may also see other negative or positive numbers (String#<=> and Integer#<=> happen to give -1, 0 and 1). The nil result means "these two are not comparable", and sort will refuse to continue when it meets one.

Making a class comparable

Here is a software version with major, minor and patch numbers. We define <=> and include Comparable:

Ruby A Version class with Comparable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Look at how little we wrote. The body of <=> reuses Array comparison: [1, 4, 2] <=> [1, 10, 0] compares the first elements, and moves on only if they are equal. That is the trick to remember for multi-field ordering, and it gives you correct numeric ordering where plain string comparison would put "1.10.0" before "1.2.0".

Notice also the guard return nil unless other.is_a?(Version). A <=> that returns nil for foreign objects makes Comparable raise a clear error instead of crashing in the middle of your method.

What Comparable gives you

Ruby Every method Comparable adds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

clamp limits a value to a range. It returns the lower bound when the value is below it, the upper bound when it is above, and the value itself otherwise, so volume.clamp(0, 100) keeps a setting within bounds in one expression. It is also available on Integer, Float and String, because they include Comparable too.

Comparable#== is derived from <=> returning 0. That is what makes five == Money.new(500) true even though they are different objects. But equal? still tells you they are not the same object, and eql? and hash are not supplied by Comparable. If you use these objects as hash keys or in a Set, define eql? and hash yourself (Equality and Identity).

Comparing in several fields

For ordering by more than one criterion, compare arrays of the fields. The array comparison does the "if equal, try the next field" logic for you. To reverse one field, negate numbers:

Ruby Multi-field ordering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Here a smaller <=> result means "ranks higher", so min returns the leader. Define the order of the class in one place, and every sort, min and max agrees. When the ordering is only needed once, a quick sort_by with an array key is lighter. Choose Comparable when the order is part of what the object is (versions, money, dates), and sort_by for ad hoc sorting.

What happens when comparison fails

If <=> returns nil, the operators built from it raise ArgumentError:

Ruby Comparing unrelated things (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints true, the second prints false (Comparable's == returns false when <=> gives nil), and the third stops the script with main.rb:13:in 'Comparable#<': comparison of Money with 5 failed (ArgumentError). Failing loudly on < is intended: "is a Money less than 5?" has no meaningful answer.

Sorting a list that holds incomparable items shows the same problem, and a plain Integer-with-String comparison fails the same way:

Ruby Sorting mixed values (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The sort_by(&:to_s) line prints [1, 3, "two"] after converting everything to strings. The plain sort stops with main.rb:3:in 'Array#sort': comparison of String with 1 failed (ArgumentError): sort tried to compare "two" with 1 and <=> answered nil. When you meet this error, find the value that returns nil from <=>. It is often a stray nil in the data; compact or a default value fixes it.

Useful patterns

Ruby clamp, between? and min/max with limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Remember that strings compare character by character, so "10" comes before "9". Convert to numbers (or to arrays of numbers, as in Version) before comparing when the data is numeric.

Design notes

  • Return nil from <=> for objects you cannot compare, rather than raising or guessing.
  • Make <=> consistent: if a <=> b is -1, then b <=> a must be 1, and it must be transitive. A broken <=> makes sort return odd results.
  • Avoid floating-point surprises: comparing floats with == after arithmetic can fail (0.1 + 0.2 == 0.3 is false). For money, store integer cents or use BigDecimal or Rational.
  • Do not override == to mean something different from <=> returning 0.
  • Comparable is for objects with a natural order. For several possible orders (by name, by date), keep one natural <=> and use sort_by for the others.
  • Another path to ordered objects is Struct and Data, which are not Comparable by default; add include Comparable and a <=> to them when it makes sense (see Struct and Data).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a <=> b return if the two objects cannot be compared?

    The spaceship operator returns -1, 0 or 1 for comparable objects and nil when no ordering exists, for example 1 <=> "one".
  2. 2. Which single method must you define before include Comparable is useful?

    Comparable builds <, <=, >, >=, ==, between? and clamp from <=>. Defining == separately is not needed.
  3. 3. What does 15.clamp(1, 10) return?

    clamp returns the upper bound when the value is above the range, the lower bound when it is below, and the value itself when it is inside.
  4. 4. Why does Money.new(5) < 5 raise ArgumentError when Money#<=> returns nil for non-Money objects?

    <, <=, > and >= treat a nil result as 'not comparable' and raise ArgumentError, while == simply returns false.
  5. 5. Which key makes sort_by order players by score descending, then by name ascending?

    Arrays compare element by element. Negating the number reverses that field, and the name breaks ties alphabetically.

Summary

  • <=> returns -1, 0, 1 or nil; include Comparable turns it into <, <=, >, >=, ==, between? and clamp.
  • Compare arrays of fields in <=> for multi-field ordering; negate a number to reverse one field.
  • Once <=> exists, sort, min, max and minmax work on arrays of your objects.
  • Return nil from <=> for foreign objects: the operators then raise ArgumentError and == returns false.
  • Comparable does not define eql? or hash; add them for hash keys and sets.
  • Use clamp to limit values to a range in one expression.

Next: Array Algorithms