Bird
0
0

Which of the following Ruby code snippets correctly demonstrates the use of ensure to guarantee execution of cleanup code?

easy📝 Syntax Q3 of 15
Ruby - Error Handling
Which of the following Ruby code snippets correctly demonstrates the use of ensure to guarantee execution of cleanup code?
A<pre>begin puts "Process" rescue puts "Error" end ensure puts "Cleanup"</pre>
B<pre>begin puts "Process" ensure puts "Always runs" end</pre>
C<pre>begin puts "Process" rescue puts "Error" ensure puts "Cleanup"</pre>
D<pre>begin puts "Process" rescue puts "Error" finally puts "Cleanup"</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Understand ensure placement

    The ensure block must be inside the begin...end block to guarantee execution.
  2. Step 2: Analyze options

    begin
      puts "Process"
    ensure
      puts "Always runs"
    end
    correctly places ensure inside begin...end.
    begin
      puts "Process"
    rescue
      puts "Error"
    end
    ensure
      puts "Cleanup"
    places ensure outside the block, which is invalid syntax.
    begin
      puts "Process"
    rescue
      puts "Error"
    ensure
      puts "Cleanup"
    is missing the closing end.
    begin
      puts "Process"
    rescue
      puts "Error"
    finally
      puts "Cleanup"
    uses finally, which is not valid Ruby syntax.
  3. Final Answer:

    It runs code regardless of whether an exception occurred or not -> Option B
  4. Quick Check:

    Ensure block must be inside begin-end [OK]
Quick Trick: Ensure must be inside begin-end block [OK]
Common Mistakes:
  • Placing ensure outside the begin-end block
  • Using finally instead of ensure
  • Omitting the end keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes