0
0
Rubyprogramming~15 mins

Spaceship operator (<=>) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Spaceship Operator (<=>) in Ruby
📖 Scenario: You are working on a simple ranking system for a game. You want to compare players' scores to see who is higher, lower, or if they are equal.
🎯 Goal: Build a Ruby program that uses the spaceship operator () to compare two player scores and print the comparison result.
📋 What You'll Learn
Create two integer variables named score1 and score2 with exact values 85 and 90 respectively.
Create a variable called comparison that stores the result of score1 <=> score2.
Use a case statement with comparison to print "score1 is less than score2", "score1 is equal to score2", or "score1 is greater than score2" based on the comparison result.
Print the final message to the console.
💡 Why This Matters
🌍 Real World
Comparing scores or rankings is common in games, leaderboards, and sorting lists.
💼 Career
Understanding comparison operators like the spaceship operator helps in writing clean and efficient sorting and comparison logic in software development.
Progress0 / 4 steps
1
Create the player scores
Create two integer variables called score1 and score2 with the exact values 85 and 90 respectively.
Ruby
Need a hint?

Use = to assign values to variables like score1 = 85.

2
Compare the scores using the spaceship operator
Create a variable called comparison that stores the result of score1 <=> score2.
Ruby
Need a hint?

The spaceship operator returns -1, 0, or 1 depending on how the two values compare.

3
Use a case statement to interpret the comparison
Use a case statement with the variable comparison to print "score1 is less than score2" if comparison is -1, "score1 is equal to score2" if 0, and "score1 is greater than score2" if 1.
Ruby
Need a hint?

The case statement helps you run different code depending on the value of comparison.

4
Print the comparison result
Run the program to print the message that shows how score1 compares to score2.
Ruby
Need a hint?

Just run the program. The puts statements inside the case will print the message.