Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Error Handling
What will be the output of this Ruby code?
attempts = 0
begin
  attempts += 1
  puts "Try #{attempts}"
  raise 'Error' if attempts < 3
rescue
  retry
end
puts 'Done'
ATry 1 Try 2 Try 3 Done
BTry 1 Try 2 Done
CTry 1 Try 2 Try 3 Try 4 Done
DTry 1 Done
Step-by-Step Solution
Solution:
  1. Step 1: Trace attempts and retry behavior

    Initially, attempts = 0. Each try increments attempts and prints it. If attempts < 3, it raises an error and retries.
  2. Step 2: Count tries until no error

    Try 1: attempts=1, error raised, retry.
    Try 2: attempts=2, error raised, retry.
    Try 3: attempts=3, no error, exits retry loop.
  3. Step 3: Final output

    Prints "Try 1", "Try 2", "Try 3", then "Done" after loop ends.
  4. Final Answer:

    Try 1 Try 2 Try 3 Done -> Option A
  5. Quick Check:

    Retries until attempts=3 = B [OK]
Quick Trick: Count retries until condition stops error [OK]
Common Mistakes:
  • Forgetting retry causes loop restart
  • Assuming fewer or more tries than 3
  • Ignoring the final puts after retry

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes