0
0
Rubyprogramming~5 mins

Spaceship operator (<=>) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the spaceship operator (<=>) do in Ruby?
It compares two values and returns -1 if the left is less, 0 if equal, and 1 if the left is greater.
Click to reveal answer
beginner
What is the return value of 5 <=> 10 in Ruby?
It returns -1 because 5 is less than 10.
Click to reveal answer
intermediate
How can the spaceship operator help in sorting arrays?
It provides a simple way to define custom comparison logic for sorting by returning -1, 0, or 1.
Click to reveal answer
beginner
What will be the result of 'apple' <=> 'banana' in Ruby?
It returns -1 because 'apple' comes before 'banana' alphabetically.
Click to reveal answer
advanced
Can the spaceship operator be used with custom objects in Ruby?
Yes, by defining the <=> method inside the object's class to specify how to compare instances.
Click to reveal answer
What does the spaceship operator (<=>) return when the left value is greater than the right?
A0
B-1
Cnil
D1
Which of these is a valid use of the spaceship operator in Ruby?
A5 => 3
B5 <=> 3
C5 =< 3
D5 ==< 3
What does the spaceship operator return if two values are equal?
A0
B1
C-1
Dnil
How can the spaceship operator be used in sorting an array?
ABy replacing the sort method
BBy using it as a method to reverse the array
CBy providing a block that returns <=> between elements
DBy converting elements to strings
What happens if you use the spaceship operator on objects without defining <=> method?
AIt returns nil
BIt returns 0
CIt raises an error
DIt always returns 1
Explain how the spaceship operator (<=>) works in Ruby and give an example.
Think about how it tells if one value is less, equal, or greater than another.
You got /3 concepts.
    Describe how you can use the spaceship operator to sort an array with custom objects.
    Custom objects need a way to compare themselves for sorting.
    You got /3 concepts.