Challenge - 5 Problems
Ensure Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat 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
Attempts:
2 left
💡 Hint
Remember that ensure runs no matter what, even if an error is raised.
✗ Incorrect
The code prints "Start" first, then raises an error. The ensure block runs next, printing "Cleanup". After that, the error is propagated, causing the RuntimeError message.
❓ Predict Output
intermediateWhat 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
Attempts:
2 left
💡 Hint
The ensure block can override the return value if it has a return statement.
✗ Incorrect
Even though the begin block returns 10, the ensure block's return 20 overrides it, so the method returns 20.
❓ Predict Output
advancedWhat 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
Attempts:
2 left
💡 Hint
Ensure runs after rescue and can change variable values.
✗ Incorrect
The begin block sets x=1 then raises an error. Rescue sets x=2. Ensure runs last and sets x=3. So x is 3 when printed.
❓ Predict Output
advancedWhat 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
Attempts:
2 left
💡 Hint
An error in ensure overrides any previous error.
✗ Incorrect
The first raise triggers "Oops" error, but the ensure block raises "Cleanup error" which overrides the first error. So the final error is "Cleanup error".
🧠 Conceptual
expertWhy use ensure instead of rescue for cleanup?
Which statement best explains why Ruby programmers use ensure blocks for cleanup instead of rescue blocks?
Attempts:
2 left
💡 Hint
Think about when cleanup code must run.
✗ Incorrect
Ensure blocks always run after the begin block, whether or not an exception was raised, making them ideal for cleanup tasks like closing files or releasing resources.
