0
0
Rubyprogramming~10 mins

Spaceship operator (<=>) in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Spaceship operator (<=>)
Compare a and b
Is a < b?
YesReturn -1
No
Is a == b?
YesReturn 0
No
Return 1 (a > b)
The spaceship operator compares two values and returns -1, 0, or 1 depending on whether the first is less than, equal to, or greater than the second.
Execution Sample
Ruby
result = 5 <=> 10
puts result
Compares 5 and 10, then prints the comparison result.
Execution Table
StepExpressionComparisonResult
15 <=> 105 < 10-1
2puts resultPrints result-1
💡 Comparison done, result printed, program ends.
Variable Tracker
VariableStartAfter ComparisonFinal
resultnil-1-1
Key Moments - 3 Insights
Why does 5 <=> 10 return -1 instead of true or false?
The spaceship operator returns -1, 0, or 1 to show order, not a boolean. See execution_table step 1 where 5 < 10 returns -1.
What happens if both values are equal?
If values are equal, the operator returns 0. This is shown in the flow where equality leads to 0.
Why is the result stored in a variable before printing?
Storing allows reuse or further checks. The execution_table shows result assigned before printing.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of 5 <=> 10 at step 1?
A0
B-1
C1
Dtrue
💡 Hint
Check the 'Result' column in execution_table row 1.
At which step is the comparison result printed?
AStep 1
BAfter program ends
CStep 2
DBefore comparison
💡 Hint
Look at the 'Expression' column for 'puts result' in execution_table.
If we compare 10 <=> 5, what would the result be?
A1
B0
C-1
Dnil
💡 Hint
Recall the spaceship operator returns 1 if the left is greater than the right.
Concept Snapshot
Spaceship operator (<=>) compares two values.
Returns -1 if left < right.
Returns 0 if left == right.
Returns 1 if left > right.
Useful for sorting and comparisons.
Syntax: a <=> b
Full Transcript
The spaceship operator in Ruby compares two values and returns -1, 0, or 1. It returns -1 if the first value is less than the second, 0 if they are equal, and 1 if the first is greater. For example, 5 <=> 10 returns -1 because 5 is less than 10. This result can be stored in a variable and printed. This operator is helpful when you want to know the order between two values, not just if one is true or false compared to the other.