Challenge - 5 Problems
Spaceship Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this spaceship operator comparison?
Consider the following Ruby code using the spaceship operator (<=>). What will be printed?
Ruby
puts 5 <=> 10
Attempts:
2 left
💡 Hint
The spaceship operator returns -1 if the left side is less than the right side.
✗ Incorrect
The spaceship operator returns -1 when the left value is smaller than the right value, 0 if equal, and 1 if greater.
❓ Predict Output
intermediate2:00remaining
What does this spaceship operator expression return?
What is the output of this Ruby code snippet?
Ruby
result = 'apple' <=> 'apple' puts result
Attempts:
2 left
💡 Hint
The spaceship operator returns 0 when both sides are equal.
✗ Incorrect
Since both strings are the same, the operator returns 0.
❓ Predict Output
advanced2:00remaining
What is the output of this spaceship operator with arrays?
What will this Ruby code print?
Ruby
puts [1, 2, 3] <=> [1, 2, 4]
Attempts:
2 left
💡 Hint
The spaceship operator compares arrays element by element.
✗ Incorrect
The first differing element is 3 vs 4, and since 3 < 4, the result is -1.
❓ Predict Output
advanced2:00remaining
What happens when comparing incompatible types with <=>?
What is the output of this Ruby code?
Ruby
puts 10 <=> '10'
Attempts:
2 left
💡 Hint
The spaceship operator returns nil when the two objects are not comparable.
✗ Incorrect
Since an integer and a string cannot be compared, the operator returns nil.
🧠 Conceptual
expert3:00remaining
How does the spaceship operator behave in custom class sorting?
Given a Ruby class with a custom <=> method, what will be the output of sorting an array of its objects?
class Box
attr_reader :volume
def initialize(volume)
@volume = volume
end
def <=>(other)
volume <=> other.volume
end
end
boxes = [Box.new(30), Box.new(10), Box.new(20)]
sorted_volumes = boxes.sort.map(&:volume)
puts sorted_volumes.inspect
Attempts:
2 left
💡 Hint
The spaceship operator defines how objects are compared during sorting.
✗ Incorrect
The custom <=> compares volumes, so sorting orders boxes by volume ascending.