Challenge - 5 Problems
If-Else Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code with if, elsif, else?
Consider the following Ruby code snippet. What will it print when run?
Ruby
score = 75 if score >= 90 puts "Excellent" elsif score >= 60 puts "Good" else puts "Needs Improvement" end
Attempts:
2 left
💡 Hint
Think about which condition matches the score 75 first.
✗ Incorrect
The score 75 is not >= 90, so the first if is false. The elsif checks if score >= 60, which is true, so it prints "Good".
❓ Predict Output
intermediate2:00remaining
What does this Ruby code print?
Look at this Ruby code using if, elsif, and else. What will be printed?
Ruby
temperature = 30 if temperature > 35 puts "It's very hot" elsif temperature > 25 puts "It's warm" elsif temperature > 15 puts "It's cool" else puts "It's cold" end
Attempts:
2 left
💡 Hint
Check the first condition that matches temperature 30.
✗ Incorrect
30 is not > 35, so first if is false. 30 > 25 is true, so it prints "It's warm" and skips the rest.
🔧 Debug
advanced2:00remaining
Why does this Ruby code raise an error?
This Ruby code is intended to print a message based on age, but it raises an error. What is the cause?
Ruby
age = 20 if age < 13 puts "Child" elsif age < 20 puts "Teenager" else puts "Adult" end
Attempts:
2 left
💡 Hint
Check if all blocks are properly closed.
✗ Incorrect
Ruby requires every if block to be closed with 'end'. This code is missing the final 'end', causing a syntax error.
🧠 Conceptual
advanced2:00remaining
What is the value of 'result' after this Ruby code runs?
Analyze the code and determine the final value of the variable 'result'.
Ruby
number = 10 result = if number > 10 "Greater" elsif number == 10 "Equal" else "Smaller" end
Attempts:
2 left
💡 Hint
Remember that if-elsif-else in Ruby returns the last evaluated expression.
✗ Incorrect
Since number == 10, the elsif condition is true, so result is assigned "Equal".
📝 Syntax
expert2:00remaining
Which option causes a syntax error in Ruby if-elsif-else statement?
Identify which code snippet will cause a syntax error when run.
Attempts:
2 left
💡 Hint
Check if all if statements are properly closed.
✗ Incorrect
Option A is missing the 'end' keyword to close the if statement, causing a syntax error.