28 June 2007 Manfred Stienstra and Thijs van der Vossen

The sort method in Ruby uses the boat operator, sometimes called ‘spaceship’, to compare object instances. In this episode Manfred shows how you can make your objects sortable by defining the boat operator.

Download episode

class Book
  attr_accessor :tokens
  def initialize(text)
    @tokens = text.downcase.split(/ /)
  end
  
  attr_writer :priority
  def priority; @priority || 0; end
  
  def <=>(other)
    if other.kind_of?(Book)
      if (important = (other.priority <=> priority)
         ) != 0
        important
      else
        tokens <=> other.tokens
      end
    else
      raise ArgumentError,
        "Don't know how to compare a #{other.class} to a Book."
    end
  end
end