Comparable (Ruby)

Comparable is a Ruby mixin that gives a class the comparison operators <, <=, ==, >, >=, plus between? and clamp — all derived from a single <=> method you define.

Ruby

Include the Comparable module and implement one method, <=> (the spaceship operator), and Ruby supplies the rest of the comparison interface for free. This is a textbook example of how mixins add a whole bundle of behavior from a minimal definition.

Your <=> should return -1, 0, or 1 by comparing whatever attributes define the natural order of your objects — often delegating to a tuple comparison of those fields. Once defined, instances also become sortable, since sort relies on <=>.

Comparable pairs conceptually with Enumerable: Comparable is for making one object orderable relative to another, while Enumerable is for iterating collections. Together they show Ruby's mixin philosophy of composing capabilities.

Syntax

class T
  include Comparable
  def <=>(other); self.value <=> other.value; end
end

Examples

Ruby

class Version
  include Comparable
  attr_reader :n
  def initialize(n); @n = n; end
  def <=>(other); n <=> other.n; end
end

puts Version.new(2) > Version.new(1)
puts [Version.new(3), Version.new(1)].min.n

Output:

true
1

Learn it in a lesson

See also

Back to the Dictionary