← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 3 of 6

Comparable

Comparable teaches a class how to compare its objects, giving it bigger and smaller checks for free. It is like showing kids how to line up by height.

In this page:

  1. Comparable
Syntax
ruby
class ClassName
  include Comparable

  def <=>(other)
    attribute <=> other.attribute
  end
end

Comparable

Mixing in the Comparable module gives a class <, >, <=, >=, ==, and .between? automatically, as long as the class defines a single <=> ("spaceship") method that returns -1, 0, or 1.

This is a good example of how a module can add a lot of functionality from a small amount of code you provide. It mirrors the role IComparable plays in some other languages.

Note: Implementing just <=> and including Comparable gets you six comparison operators plus .between? for free.

Example: Comparable

markup
class Money
  include Comparable
  attr_reader :amount

  def initialize(amount)
    @amount = amount
  end

  def <=>(other)
    amount <=> other.amount
  end
end

a = Money.new(10)
b = Money.new(20)

puts a < b
puts a.between?(Money.new(5), Money.new(15))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Including Comparable without defining <=>, so < and > raise errors.
  2. Returning true or false from <=>, when it must return -1, 0, 1 (or nil).
  3. Comparing with an object of another type in <=>, which raises an error when other.amount is missing.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.