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

Comparable

In this page:

  1. Comparable

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))
🔒

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.