Spaceship Operator in Ruby: What It Is and How to Use It
spaceship operator (<=>) in Ruby is used to compare two values and returns -1, 0, or 1 depending on whether the first value is less than, equal to, or greater than the second. It is a concise way to perform three-way comparisons in sorting and conditional logic.How It Works
The spaceship operator <=> compares two values and tells you their order by returning one of three numbers: -1 if the first value is smaller, 0 if they are equal, and 1 if the first is larger. Think of it like a referee deciding who wins between two players: it says who is ahead, or if they are tied.
This operator is very useful when you want to sort items or decide order because it gives a clear, simple answer about how two things relate to each other. Instead of writing multiple if-else checks, you get a single number that sums up the comparison.
Example
puts 5 <=> 10 puts 10 <=> 10 puts 15 <=> 10 puts 'apple' <=> 'banana' puts 'cat' <=> 'cat'
When to Use
Use the spaceship operator when you need to compare two values quickly and clearly, especially in sorting algorithms or custom comparison methods. For example, Ruby’s built-in sorting methods use it to decide how to order elements.
It is also helpful when writing your own comparison logic for objects, so you can define how they should be ordered or checked for equality in a simple, consistent way.
Key Points
- The spaceship operator returns -1, 0, or 1 to show order between two values.
- It simplifies comparison logic by combining less than, equal, and greater than checks.
- Commonly used in sorting and custom comparison methods.
- Works with numbers, strings, and many Ruby objects that support comparison.