📖 Scenario: Imagine you have a simple task that might fail sometimes, like trying to connect to a website. You want to try again if it fails, but only a few times.
🎯 Goal: You will write a Ruby program that tries to perform a task and uses retry to attempt it again if it fails, up to a limit.
📋 What You'll Learn
Create a variable called attempts to count tries
Create a variable called max_attempts set to 3
Write a begin block with a simulated failure using raise
Use rescue to catch the error and use retry to try again
Print a success message if the task succeeds
💡 Why This Matters
🌍 Real World
Retrying is useful when working with unreliable tasks like network requests or reading files, where temporary failures happen.
💼 Career
Understanding retry logic helps in writing robust programs that handle errors gracefully and improve user experience.
Progress0 / 4 steps
1
Set up the attempt counter
Create a variable called attempts and set it to 0.
Ruby
Hint
Use = to assign 0 to attempts.
2
Set the maximum number of attempts
Create a variable called max_attempts and set it to 3.
Ruby
Hint
Use = to assign 3 to max_attempts.
3
Write the retry logic with begin-rescue
Write a begin block that increases attempts by 1, then raises an exception if attempts is less than max_attempts. Use rescue to catch the exception, print "Attempt failed", and use retry to try again.
Ruby
Hint
Use begin and rescue to handle errors. Increase attempts inside begin. Use raise to simulate failure. Use retry inside rescue to try again.
4
Print success message after retries
After the begin-rescue-end block, write puts "Task succeeded on attempt #{attempts}" to print a success message showing the attempt number.
Ruby
Hint
Use puts with an f-string style #{} to show the attempt number.
Practice
(1/5)
1. What does the retry keyword do in Ruby when used inside a rescue block?
easy
A. It skips the current error and continues after the rescue block.
B. It restarts the code inside the begin block from the beginning.
C. It stops the program immediately without handling the error.
D. It logs the error and moves to the next line of code.
Solution
Step 1: Understand retry usage context
The retry keyword is used inside a rescue block to repeat the code in the begin block.
Step 2: Effect of retry
When an error occurs and retry is called, Ruby restarts the begin block from the start, trying again.
Final Answer:
It restarts the code inside the begin block from the beginning. -> Option B
Quick Check:
retry restarts code = A [OK]
Hint: Retry restarts the begin block after an error [OK]
Common Mistakes:
Thinking retry skips the error without retrying
Assuming retry stops the program
Confusing retry with error logging
2. Which of the following is the correct syntax to retry a block after rescuing an exception in Ruby?
easy
A. retry
begin
# code
rescue
end
B. begin
# code
retry
rescue
end
C. begin
# code
rescue
retry
end
D. begin
retry
# code
rescue
end
Solution
Step 1: Identify correct retry placement
The retry keyword must be inside the rescue block to reattempt the begin block.
Step 2: Check syntax correctness
begin
# code
rescue
retry
end places retry inside rescue, which is the correct syntax.
Final Answer:
begin
# code
rescue
retry
end -> Option C
Quick Check:
retry inside rescue = D [OK]
Hint: Retry must be inside rescue block after begin [OK]
Common Mistakes:
Placing retry outside rescue block
Putting retry before begin block
Using retry without rescue
3. 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'
medium
A. Try 1
Try 2
Try 3
Done
B. Try 1
Try 2
Done
C. Try 1
Try 2
Try 3
Try 4
Done
D. Try 1
Done
Solution
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.
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.