0
0
Rubyprogramming~20 mins

Spaceship operator (<=>) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Spaceship Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A1
B0
Cnil
D-1
Attempts:
2 left
💡 Hint
The spaceship operator returns -1 if the left side is less than the right side.
Predict Output
intermediate
2:00remaining
What does this spaceship operator expression return?
What is the output of this Ruby code snippet?
Ruby
result = 'apple' <=> 'apple'
puts result
A-1
B0
C1
Dnil
Attempts:
2 left
💡 Hint
The spaceship operator returns 0 when both sides are equal.
Predict Output
advanced
2: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]
A-1
B0
C1
Dnil
Attempts:
2 left
💡 Hint
The spaceship operator compares arrays element by element.
Predict Output
advanced
2:00remaining
What happens when comparing incompatible types with <=>?
What is the output of this Ruby code?
Ruby
puts 10 <=> '10'
Anil
B1
C-1
D0
Attempts:
2 left
💡 Hint
The spaceship operator returns nil when the two objects are not comparable.
🧠 Conceptual
expert
3: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
A[30, 20, 10]
BRaises an error
C[10, 20, 30]
D[20, 10, 30]
Attempts:
2 left
💡 Hint
The spaceship operator defines how objects are compared during sorting.