Codectionary / Developer documentation / Ruby

Comparable Domain Objects

Comparable derives comparison operators from a class’s <=> method. Return nil for objects that cannot be compared meaningfully. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

include Comparable; def <=>(other); key <=> other.key; end

Examples

Comparable Domain Objects

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

class Score
  include Comparable
  attr_reader :points
  def initialize(points)
    @points = points
  end
  def <=>(other)
    return nil unless other.is_a?(Score)
    points <=> other.points
  end
end
puts Score.new(8) > Score.new(3)
puts Score.new(5).between?(Score.new(3), Score.new(8))
  1. Expected output: true true
  2. The spaceship operator compares numeric points. Comparable reuses that ordering for > and between?.

Best practices

  • Make comparison transitive and consistent across accepted operand types.
  • Define equality and hashing deliberately if objects are also used as Hash keys or Set members.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading