Recall & Review
beginner
What does the
retry keyword do in Ruby?The
retry keyword restarts the execution of the begin block from the start, allowing you to try the code again after an exception.Click to reveal answer
beginner
Where can you use
retry in Ruby code?You can use
retry inside a rescue block to reattempt the code inside the begin block after an error occurs.Click to reveal answer
intermediate
What happens if
retry is used outside a rescue block?Using
retry outside a rescue block causes a syntax error because Ruby expects it only to be used for reattempting after an exception.Click to reveal answer
intermediate
How can you limit the number of retries in Ruby?
You can use a counter variable to track how many times you retried and use
retry only if the count is below a limit, preventing infinite loops.Click to reveal answer
beginner
Example: What will this code print?
attempt = 0
begin
attempt += 1
puts "Try #{attempt}"
raise "Fail" if attempt < 3
rescue
retry
end
puts "Success on try #{attempt}"The code prints:<br>Try 1<br>Try 2<br>Try 3<br>Success on try 3<br>It retries twice after failures and succeeds on the third try.
Click to reveal answer
What does
retry do inside a rescue block?✗ Incorrect
retry restarts the begin block, allowing the code to try again.What happens if
retry is used outside a rescue block?✗ Incorrect
retry must be inside a rescue block; otherwise, Ruby raises a syntax error.How can you prevent infinite retries when using
retry?✗ Incorrect
A counter variable helps limit how many times
retry is called.Which keyword is paired with
retry to handle errors?✗ Incorrect
retry is used inside rescue blocks to reattempt the begin block.What will happen if
retry is called without any exception being raised?✗ Incorrect
retry is only valid after an exception; calling it otherwise causes an error.Explain how the
retry keyword works in Ruby and when you would use it.Think about what happens after an error and how you can try again.
You got /4 concepts.
Describe a safe way to use
retry to avoid infinite loops.Consider counting how many times you tried.
You got /4 concepts.