0
0
Rubyprogramming~5 mins

Ensure for cleanup in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the ensure block in Ruby?
The ensure block runs code that must execute no matter what happens in the begin block, such as cleaning up resources or closing files.
Click to reveal answer
beginner
How does ensure differ from rescue in Ruby?
rescue handles exceptions when they occur, while ensure always runs after begin, whether an exception happened or not.
Click to reveal answer
intermediate
What happens if an exception is raised inside an ensure block?
If an exception occurs inside ensure, it will override any previous exception and propagate up, potentially hiding the original error.
Click to reveal answer
beginner
Why is ensure useful for resource cleanup?
ensure guarantees that cleanup code like closing files or releasing locks runs even if an error interrupts normal flow.
Click to reveal answer
beginner
Example: What will this Ruby code print?
begin
  puts 'Start'
  raise 'Oops'
rescue
  puts 'Rescued'
ensure
  puts 'Always runs'
end
It prints:<br>Start<br>Rescued<br>Always runs<br>The ensure block runs last no matter what.
Click to reveal answer
What does the ensure block guarantee in Ruby?
ACode inside it runs before the <code>begin</code> block
BCode inside it runs only if no exception occurs
CCode inside it runs only if an exception occurs
DCode inside it always runs, even if an exception occurs
Which block handles exceptions in Ruby?
A<code>begin</code>
B<code>ensure</code>
C<code>rescue</code>
D<code>finally</code>
If an exception is raised in ensure, what happens?
AIt replaces any previous exception
BThe program exits silently
CIt is caught by <code>rescue</code>
DIt is ignored
Where should you put code to close a file to ensure it always runs?
AInside <code>begin</code>
BInside <code>ensure</code>
CInside <code>rescue</code>
DOutside all blocks
What will this code print?
begin
  puts 'Hello'
ensure
  puts 'Goodbye'
end
AHello Goodbye
BGoodbye
CHello
DGoodbye Hello
Explain how the ensure block works in Ruby and why it is important for cleanup.
Think about what happens when errors occur and you still want to clean up.
You got /4 concepts.
    Describe the difference between rescue and ensure blocks in Ruby exception handling.
    One catches errors, the other guarantees code runs.
    You got /4 concepts.