Bird
0
0

You want to write a method that returns early if a user is not authorized, otherwise processes data. Which guard clause is best?

hard📝 Application Q8 of 15
Ruby - Control Flow
You want to write a method that returns early if a user is not authorized, otherwise processes data. Which guard clause is best?
def process(user, data)
  # guard clause here
  "Processing data for #{user}"
end
Areturn "Unauthorized" if user.authorized?
Bif user.authorized? then return "Unauthorized" end
Creturn "Unauthorized" if !user.authorized? == false
Dreturn "Unauthorized" unless user.authorized?
Step-by-Step Solution
Solution:
  1. Step 1: Understand authorization logic

    We want to return "Unauthorized" if user is NOT authorized.
  2. Step 2: Check guard clause options

    return "Unauthorized" unless user.authorized? uses 'return "Unauthorized" unless user.authorized?' which means return if user is not authorized, correct logic.
  3. Final Answer:

    return "Unauthorized" unless user.authorized? -> Option D
  4. Quick Check:

    Use 'unless' to return early on negative condition [OK]
Quick Trick: Use 'return ... unless condition' for negative guard clauses [OK]
Common Mistakes:
  • Reversing condition logic
  • Using if with wrong condition
  • Overcomplicating boolean expressions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes