0
0
Rubyprogramming~20 mins

Retry for reattempting in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Retry Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this retry example?
Consider the following Ruby code using retry. What will it print?
Ruby
count = 0
begin
  count += 1
  puts "Attempt #{count}"
  raise 'fail' if count < 3
rescue
  retry
end
puts 'Done'
A
Attempt 1
Attempt 2
Attempt 3
Done
B
Attempt 1
Done
C
Attempt 1
Attempt 2
Done
D
Attempt 1
Attempt 2
Attempt 3
Attempt 4
Done
Attempts:
2 left
💡 Hint
The retry keyword restarts the begin block after rescue.
Predict Output
intermediate
1:30remaining
What happens if retry is used outside rescue?
What error does this Ruby code produce?
Ruby
retry
ALocalJumpError
BRuntimeError
CSyntaxError
DNoMethodError
Attempts:
2 left
💡 Hint
retry can only be used inside rescue blocks.
🔧 Debug
advanced
2:30remaining
Why does this retry loop never end?
Look at this code. Why does it print 'Trying...' forever?
Ruby
attempts = 0
begin
  attempts = 0
  attempts += 1
  puts 'Trying...'
  raise 'error'
rescue
  retry if attempts < 5
end
puts 'Finished'
ABecause the condition to stop retry is never met
BBecause retry restarts the begin block without changing attempts
CBecause attempts is reset to 0 on each retry
DBecause retry is inside rescue and causes infinite recursion
Attempts:
2 left
💡 Hint
Check if attempts changes between retries.
📝 Syntax
advanced
1:30remaining
Which option causes a syntax error related to retry?
Which of these Ruby snippets will cause a syntax error?
A
begin
  raise 'fail'
rescue
  puts 'error'
  retry
end
B
begin
  raise 'fail'
rescue
  retry
end
C
begin
  raise 'fail'
rescue
  retry if true
end
D
begin
  retry
rescue
  puts 'error'
end
Attempts:
2 left
💡 Hint
retry must be inside rescue block, not before it.
🚀 Application
expert
3:00remaining
How many times does this retry block execute?
Given this Ruby code, how many times will 'Processing...' be printed?
Ruby
count = 0
begin
  count += 1
  puts 'Processing...'
  raise 'error' if count < 4
rescue
  retry
end
AInfinite loop
B4
C5
D3
Attempts:
2 left
💡 Hint
Does the retry condition ever stop?