Prints "Try 1", "Try 2", "Try 3", then "Done" after loop ends.
Final Answer:
Try 1
Try 2
Try 3
Done -> Option A
Quick Check:
Retries until attempts=3 = B [OK]
Hint: 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
4. Identify the error in this Ruby code using retry:
begin
puts 'Start'
raise 'Oops'
rescue
puts 'Error caught'
retry
puts 'After retry'
end
medium
A. The puts 'After retry' statement is unreachable after retry.
B. retry cannot be used inside rescue block.
C. Missing end for begin block.
D. The raise statement should be inside rescue.
Solution
Step 1: Analyze retry placement
The retry statement causes the code to jump back to begin, so any code after retry in rescue is never run.
Step 2: Identify unreachable code
The line puts 'After retry' is after retry and will never execute, making it unreachable.
Final Answer:
The puts 'After retry' statement is unreachable after retry. -> Option A
Quick Check:
Code after retry is unreachable = A [OK]
Hint: Code after retry in rescue is never executed [OK]
Common Mistakes:
Thinking retry can't be inside rescue
Ignoring unreachable code warnings
Misplacing raise statement
5. 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
A. attempts = 0
begin
# risky code
attempts += 1
rescue
retry if attempts < 3
end
B. attempts = 0
begin
attempts += 1
# risky code
rescue
retry
end
C. attempts = 0
begin
# risky code
rescue
retry unless attempts > 3
end
D. attempts = 0
begin
# risky code
rescue
attempts += 1
retry if attempts < 3
end
Solution
Step 1: Understand retry with counter
We must increment attempts inside rescue to count retries after errors.
Step 2: Check retry condition
Retry only if attempts < 3 to limit retries to 3 times.
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.
Final Answer:
attempts = 0
begin
# risky code
rescue
attempts += 1
retry if attempts < 3
end -> Option D
Quick Check:
Increment attempts in rescue before retry = C [OK]
Hint: Increment attempts in rescue before retry condition [OK]
Common Mistakes:
Incrementing attempts before begin block
Retrying without limiting attempts
Using wrong retry condition logic
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.