liveBook · Manning

Comparison

As explained in The Well-Grounded Rubyist, Fourth Edition

A comparison operator is Ruby syntax that compares two values or objects for ordering or equality.

Ruby objects can define methods for equality and ordering. The commonly used `==` belongs to a family that also includes `!=`, `<`, `>`, `<=`, and `>=`; a class need not define every comparison if those comparisons do not make sense for its objects. section 7.6 section 7.6.2

To give a class the full comparison suite:

  • Include Ruby’s `Comparable` module in the class. section 7.6.2
  • Define the instance method `<=>` to compare two objects. Return a negative number for less than, zero for equal, or a positive number for greater than. section 7.6.2
Listing 7.2 Example of a class that mixes in the Comparable module
class Bid
  include Comparable
  attr_accessor :estimate
  def <=>(other_bid)                            1
    if self.estimate < other_bid.estimate
      -1
    elsif self.estimate > other_bid.estimate
      1
    else
      0
    end
  end
end

This Bid class compares objects by their estimates, letting bids use operators such as `<`. section 7.6.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Shows a Bid implementation, the spaceship method’s return convention, and a shorter delegation to numeric estimates.
Examples
Uses bids ordered by estimates and notes that strings compare for equality and order.
What you can do after
Build from scratch a class whose objects support Ruby comparison operators by defining `<=>` and including Comparable.
How it connects
Connects equality operators, the spaceship operator, and the Comparable module.

Also explained in

Compare how 8 books explain comparison →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.