0
0
Rubyprogramming~5 mins

Spaceship operator (<=>) in Ruby

Choose your learning style9 modes available
Introduction

The spaceship operator helps compare two values easily by telling if one is smaller, equal, or bigger than the other.

When you want to sort a list of numbers or words.
When you need to check if one value is less than, equal to, or greater than another.
When writing custom comparison methods for sorting objects.
When you want a simple way to compare two things in one step.
Syntax
Ruby
a <=> b

Returns -1 if a is less than b.

Returns 0 if a equals b.

Returns 1 if a is greater than b.

Returns nil if the values cannot be compared.

Examples
5 is less than 10, so it returns -1.
Ruby
5 <=> 10  # returns -1
Both numbers are equal, so it returns 0.
Ruby
10 <=> 10  # returns 0
15 is greater than 10, so it returns 1.
Ruby
15 <=> 10  # returns 1
Strings are compared alphabetically; "apple" comes before "banana".
Ruby
"apple" <=> "banana"  # returns -1
Sample Program

This program compares numbers and words using the spaceship operator and prints the results.

Ruby
puts 3 <=> 7
puts 7 <=> 7
puts 9 <=> 7
puts "cat" <=> "dog"
puts "dog" <=> "cat"
OutputSuccess
Important Notes

The spaceship operator is very useful for sorting because it gives a clear order between two items.

If you compare things that cannot be ordered, like a number and a string, it returns nil.

Summary

The spaceship operator compares two values and returns -1, 0, or 1.

It helps decide if one value is smaller, equal, or bigger than another.

It is often used in sorting and custom comparisons.