Comparisons with the Ruby spaceship operator

The spaceship operator (<=>) is a comparison operator that is implemented by Ruby’s Comparable mixin. With the spaceship operator you can do a three-way comparison, to do the comparisons <, ==, and > in a single operation. It returns either -1, 0 or 1 depending on if the other object is respectively; less than, equal to, or greater than the other object.

With strings, where the string length is used for the comparison, it gives the following results for example.

puts 'a' <=> 'ab'   # => -1
puts 'ab' <=> 'ab'  # =>  0
puts 'ab' <=> 'a'   # =>  1

This is internally used by Ruby for sorting arrays. Ruby will swap the places of two adjacent elements in an array if the <=> comparison has a result of 1. If the result is either -1 or 0 it will leave the elements in place.

letters = ['ab', 'a', 'abc']
puts letters.sort!.inspect
# => ["a", "ab", "abc"]

Implementing the Comparable mixin

You can include the Comparable mixin in your own classes too. If you do so you get the implementation for the conventional comparison operators (<, <=, ==, >=, and >) and the method between? for free, since these make use of the <=> operator. Unless you overwrite them.

class Book
  include Comparable
  attr :pages

  def <=>(other)
    pages <=> other.pages
  end

  def initialize(str)
    @str = str
  end
end

You should return nil if the objects are not comparable using the <=> operator.

See Also

6 Non-Programming Books for Programmers