Challenge - 5 Problems
Ruby Guard Clauses Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method using guard clauses
What is the output of this Ruby method when called with the argument 5?
Ruby
def check_number(num) return "Too small" if num < 3 return "Too large" if num > 10 "Just right" end puts check_number(5)
Attempts:
2 left
💡 Hint
Look at the conditions and see which guard clause applies for 5.
✗ Incorrect
The method returns early if the number is less than 3 or greater than 10. Since 5 is between 3 and 10, it reaches the last line returning "Just right".
❓ Predict Output
intermediate2:00remaining
Return value with multiple guard clauses
What will this Ruby method return when called with the argument 0?
Ruby
def status_code(code) return "Error" if code < 0 return "Success" if code == 0 "Unknown" end puts status_code(0)
Attempts:
2 left
💡 Hint
Check which guard clause matches the input 0.
✗ Incorrect
The method returns "Success" immediately if the code equals 0, so it does not reach the last line.
🔧 Debug
advanced2:00remaining
Identify the error in guard clause usage
What error will this Ruby code raise when executed?
Ruby
def process(value) return "No value" unless value return "Zero" if value == 0 value * 2 end puts process(nil)
Attempts:
2 left
💡 Hint
Check the guard clause with 'unless value' and what happens with nil.
✗ Incorrect
The guard clause returns "No value" immediately if value is nil (which is falsey), so no error occurs.
❓ Predict Output
advanced2:00remaining
Output of method with nested guard clauses
What is the output of this Ruby method when called with argument 15?
Ruby
def evaluate(num) return "Negative" if num < 0 return "Small" if num < 10 return "Medium" if num < 20 "Large" end puts evaluate(15)
Attempts:
2 left
💡 Hint
Check each guard clause in order for 15.
✗ Incorrect
15 is not less than 0 or 10, but it is less than 20, so the method returns "Medium".
❓ Predict Output
expert3:00remaining
Return value with complex guard clauses and side effects
What will be printed when this Ruby code runs?
Ruby
def complex_check(x) return "Negative" if x < 0 puts "Checking zero" return "Zero" if x == 0 return "Positive" if x > 0 "Unknown" end result = complex_check(0) puts result
Attempts:
2 left
💡 Hint
Notice the puts inside the method before the guard clause for zero.
✗ Incorrect
When x is 0, the method prints "Checking zero" then returns "Zero", so the output is two lines: first the printed string, then the returned string printed outside.