0
0
Rubyprogramming~10 mins

Retry for reattempting in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to retry the block 3 times.

Ruby
retry_count = 0
begin
  puts 'Trying...'
  raise 'Error' if retry_count < 2
rescue
  retry_count += 1
  [1]
end
Drag options to blanks, or click blank then click option'
Anext
Bretry
Cbreak
Dredo
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'next' instead of 'retry' causes a syntax error.
Using 'break' exits the block instead of retrying.
2fill in blank
medium

Complete the code to retry only if the error message is 'Temporary failure'.

Ruby
begin
  puts 'Attempting...'
  raise 'Temporary failure'
rescue => e
  if e.message == [1]
    retry
  end
end
Drag options to blanks, or click blank then click option'
A"Temporary failure"
B"Permanent failure"
C'Temporary failure'
D'Permanent failure'
Attempts:
3 left
💡 Hint
Common Mistakes
Using single quotes instead of double quotes causes mismatch.
Comparing with wrong error message string.
3fill in blank
hard

Fix the error in the retry logic to avoid infinite loop.

Ruby
attempts = 0
begin
  attempts += 1
  puts "Try #{attempts}"
  raise 'Fail' if attempts < 3
rescue
  if attempts < 3
    [1]
  else
    puts 'Giving up'
  end
end
Drag options to blanks, or click blank then click option'
Aredo
Bnext
Cbreak
Dretry
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'redo' causes infinite loop without incrementing attempts.
Using 'next' or 'break' causes syntax errors here.
4fill in blank
hard

Fill both blanks to retry only up to 5 times and print a message each retry.

Ruby
max_retries = 5
tries = 0
begin
  tries += 1
  puts "Attempt #{tries}"
  raise 'Error' if tries < max_retries
rescue
  if tries < [1]
    puts 'Retrying...'
    [2]
  else
    puts 'No more retries'
  end
end
Drag options to blanks, or click blank then click option'
Amax_retries
Bretry
Ctries
Dbreak
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'tries' instead of 'max_retries' causes wrong retry limit.
Using 'break' instead of 'retry' stops retries prematurely.
5fill in blank
hard

Fill all three blanks to retry only when error message is 'Timeout', up to 3 times, and print attempts.

Ruby
max_attempts = 3
count = 0
begin
  count += 1
  puts "Attempt #{count}"
  raise 'Timeout' if count < max_attempts
rescue => e
  if e.message == [1] && count < [2]
    puts 'Retrying due to timeout'
    [3]
  else
    puts 'Stopping retries'
  end
end
Drag options to blanks, or click blank then click option'
A"Timeout"
Bmax_attempts
Cretry
D"Error"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong error message string causes no retry.
Not limiting retries causes infinite loop.
Using 'break' instead of 'retry' stops retries.