Bird
0
0

You want to retry a block up to 3 times if an error occurs, then stop retrying. Which code correctly implements this in Ruby?

hard📝 Application Q15 of 15
Ruby - Error Handling
You want to retry a block up to 3 times if an error occurs, then stop retrying. Which code correctly implements this in Ruby?
Aattempts = 0 begin # risky code attempts += 1 rescue retry if attempts < 3 end
Battempts = 0 begin attempts += 1 # risky code rescue retry end
Cattempts = 0 begin # risky code rescue retry unless attempts > 3 end
Dattempts = 0 begin # risky code rescue attempts += 1 retry if attempts < 3 end
Step-by-Step Solution
Solution:
  1. Step 1: Understand retry with counter

    We must increment attempts inside rescue to count retries after errors.
  2. Step 2: Check retry condition

    Retry only if attempts < 3 to limit retries to 3 times.
  3. Step 3: Verify code correctness

    attempts = 0 begin # risky code rescue attempts += 1 retry if attempts < 3 end increments attempts in rescue and retries if attempts < 3, correctly limiting retries.
  4. Final Answer:

    attempts = 0 begin # risky code rescue attempts += 1 retry if attempts < 3 end -> Option D
  5. Quick Check:

    Increment attempts in rescue before retry = C [OK]
Quick Trick: Increment attempts in rescue before retry condition [OK]
Common Mistakes:
  • Incrementing attempts before begin block
  • Retrying without limiting attempts
  • Using wrong retry condition logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes