0
0
Rubyprogramming~20 mins

Ensure for cleanup in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ensure Mastery Badge
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 Ruby code using ensure?
Consider the following Ruby code snippet. What will it print when run?
Ruby
def test_ensure
  begin
    puts "Start"
    raise "Error occurred"
  ensure
    puts "Cleanup"
  end
end

test_ensure
AStart\nRuntimeError: Error occurred
BStart\nCleanup
CCleanup\nStart\nRuntimeError: Error occurred
DStart\nCleanup\nRuntimeError: Error occurred
Attempts:
2 left
💡 Hint
Remember that ensure runs no matter what, even if an error is raised.
Predict Output
intermediate
2:00remaining
What value does the method return with ensure?
What will the following Ruby method return when called?
Ruby
def return_test
  begin
    return 10
  ensure
    return 20
  end
end

return_test
A20
B10
Cnil
DRuntimeError
Attempts:
2 left
💡 Hint
The ensure block can override the return value if it has a return statement.
Predict Output
advanced
2:00remaining
What is the output and final value of x?
Analyze this Ruby code. What is printed and what is the final value of x after execution?
Ruby
x = 0
begin
  x = 1
  raise "fail"
rescue
  x = 2
ensure
  x = 3
end
puts x
A1
B3
C2
DRuntimeError
Attempts:
2 left
💡 Hint
Ensure runs after rescue and can change variable values.
Predict Output
advanced
2:00remaining
What error does this code raise?
What error, if any, will this Ruby code raise?
Ruby
def test
  begin
    raise "Oops"
  ensure
    raise "Cleanup error"
  end
end

test
ANo error, method returns normally
BRuntimeError: Oops
CRuntimeError: Cleanup error
DSyntaxError
Attempts:
2 left
💡 Hint
An error in ensure overrides any previous error.
🧠 Conceptual
expert
2:00remaining
Why use ensure instead of rescue for cleanup?
Which statement best explains why Ruby programmers use ensure blocks for cleanup instead of rescue blocks?
AEnsure runs regardless of whether an exception occurs, guaranteeing cleanup code always executes.
BRescue runs only if no exception occurs, so it is unreliable for cleanup.
CRescue blocks run before the main code, so they cannot clean up after it.
DEnsure blocks catch exceptions and prevent program crashes.
Attempts:
2 left
💡 Hint
Think about when cleanup code must run.