What Is the Ruby Spaceship Operator (<=>)?

The Ruby spaceship operator (<=>) is a comparison operator often used for sorting and comparing objects. It returns one of the following three values:

  1. -1 — if the left operand is less than the right operand;
  2. 0 — if both operands are equal;
  3. 1 — if the left operand is greater than the right operand.

The spaceship operator is typically used in situations where you want to compare two values, such as when sorting an array of objects. When you provide a block or use the spaceship operator within a sorting method (like Array#sort) it allows you to determine the order of elements based on the values returned by the <=> operator.

For example, you can sort an array of numbers in ascending order using the spaceship operator like so:

numbers = [5, 2, 8, 1, 9]

sorted_numbers = numbers.sort { | a, b | a <=> b }

puts sorted_numbers #=> [1, 2, 5, 8, 9]

In this example, the spaceship operator compares each pair of elements in the array and returns -1, 0, or 1 based on the comparison result, allowing the Array#sort method to arrange the elements in ascending order.

By default, the spaceship operator (<=>) works for numbers, strings and arrays. You can also use it with objects of custom classes by implementing the <=> method within your class. This allows you to define the comparison logic for your objects.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.