0
0
Rubyprogramming~20 mins

Guard clauses pattern in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Guard Clauses Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
AJust right
BToo large
CToo small
Dnil
Attempts:
2 left
💡 Hint
Look at the conditions and see which guard clause applies for 5.
Predict Output
intermediate
2: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)
AError
BUnknown
CSuccess
Dnil
Attempts:
2 left
💡 Hint
Check which guard clause matches the input 0.
🔧 Debug
advanced
2: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)
ANoMethodError
BTypeError
CArgumentError
DNo error, outputs "No value"
Attempts:
2 left
💡 Hint
Check the guard clause with 'unless value' and what happens with nil.
Predict Output
advanced
2: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)
AMedium
BNegative
CSmall
DLarge
Attempts:
2 left
💡 Hint
Check each guard clause in order for 15.
Predict Output
expert
3: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
A
Negative
Negative
B
Checking zero
Zero
C
Zero
Zero
D
Checking zero
Positive
Attempts:
2 left
💡 Hint
Notice the puts inside the method before the guard clause for zero.