📖 Scenario: Imagine you are writing a small Ruby program that opens a file, writes some text, and then closes the file. You want to make sure the file is always closed, even if something goes wrong while writing.
🎯 Goal: You will create a Ruby program that uses begin, rescue, and ensure blocks to handle errors and always close the file.
📋 What You'll Learn
Create a variable called file that opens a file named example.txt for writing.
Create a variable called text_to_write with the value 'Hello, Ruby!'.
Use a begin block to write text_to_write to file.
Add a rescue block to catch any exceptions and print 'An error occurred.'.
Add an ensure block that closes the file.
Print 'File closed.' after the ensure block.
💡 Why This Matters
🌍 Real World
In real programs, files and other resources must be closed properly to avoid problems like data loss or locked files. Using <code>ensure</code> helps keep your program safe and clean.
💼 Career
Understanding error handling and cleanup with <code>ensure</code> is important for writing reliable Ruby programs, which is a valuable skill for software developers and engineers.
Progress0 / 4 steps
1
Open the file and prepare text
Create a variable called file that opens a file named example.txt for writing using File.open. Then create a variable called text_to_write and set it to 'Hello, Ruby!'.
Ruby
Hint
Use File.open('example.txt', 'w') to open the file for writing.
2
Start the begin block and write to the file
Add a begin block. Inside it, write text_to_write to file using file.write(text_to_write).
Ruby
Hint
Use begin to start the block and file.write(text_to_write) to write.
3
Add rescue block to handle errors
Add a rescue block after the begin block. Inside it, print 'An error occurred.' using puts.
Ruby
Hint
Use rescue to catch errors and puts to print the message.
4
Add ensure block to close file and print confirmation
Add an ensure block after the rescue block. Inside it, close the file using file.close. Then print 'File closed.' using puts.
Ruby
Hint
Use ensure to always run code, close the file with file.close, and print the message.
Practice
(1/5)
1. What is the main purpose of the ensure block in Ruby?
easy
A. To run code that must execute regardless of errors
B. To catch exceptions and handle them
C. To define a method inside a class
D. To start a loop that repeats code
Solution
Step 1: Understand the role of ensure
The ensure block runs code no matter what happens in the begin block, even if an error occurs.
Step 2: Compare with other blocks
Unlike rescue which handles errors, ensure always runs for cleanup tasks.
Final Answer:
To run code that must execute regardless of errors -> Option A
Quick Check:
ensure = always runs cleanup [OK]
Hint: Remember: ensure always runs, even after errors [OK]
Common Mistakes:
Confusing ensure with rescue
Thinking ensure only runs on errors
Using ensure to catch exceptions
2. Which of the following is the correct syntax to use ensure in Ruby?
easy
A. if
# code
else
# cleanup code
end
B. try
# code
finally
# cleanup code
end
C. begin
# code
rescue
# cleanup code
end
D. begin
# code
ensure
# cleanup code
end
Solution
Step 1: Identify Ruby's syntax for ensure
Ruby uses begin ... ensure ... end to guarantee cleanup code runs.
Step 2: Eliminate other language or incorrect syntax
Options B and D use non-Ruby keywords; C uses rescue which is for error handling, not guaranteed cleanup.
Final Answer:
begin
# code
ensure
# cleanup code
end -> Option D
Quick Check:
Ruby ensure syntax = begin ... ensure ... end [OK]
Hint: Use begin ... ensure ... end for guaranteed cleanup [OK]
Common Mistakes:
Using try/finally (not Ruby syntax)
Confusing rescue with ensure
Using if/else for cleanup
3. What will be the output of this Ruby code?
def test
begin
puts "Start"
raise "Error!"
ensure
puts "Cleanup"
end
end
test
medium
A. Start\nCleanup\nRuntimeError: Error!
B. Start\nRuntimeError: Error!\nCleanup
C. Cleanup\nStart\nRuntimeError: Error!
D. Start\nCleanup
Solution
Step 1: Trace the code execution
The method prints "Start", then raises an error. The ensure block runs next, printing "Cleanup".
Step 2: Understand error propagation
After ensure, the error is not rescued, so it propagates and shows the RuntimeError message.
Final Answer:
Start\nCleanup\nRuntimeError: Error! -> Option A
Quick Check:
ensure runs before error propagates [OK]
Hint: Ensure runs before error stops program [OK]
Common Mistakes:
Thinking ensure stops error
Assuming cleanup prints after error message
Ignoring error propagation
4. Identify the error in this Ruby code using ensure:
begin
puts "Processing"
# missing end for begin
ensure
puts "Cleaning up"
end
medium
A. Cannot use ensure without rescue
B. Missing end for begin block
C. The puts statements are invalid inside ensure
D. The ensure block must come before begin
Solution
Step 1: Check block structure
The begin block is missing its closing end before ensure.
Step 2: Understand ensure placement
ensure must be inside the begin ... end block, so the missing end causes a syntax error.
Final Answer:
Missing end for begin block -> Option B
Quick Check:
Every begin needs matching end [OK]
Hint: Count your begin and end keywords carefully [OK]
Common Mistakes:
Thinking ensure needs rescue
Placing ensure outside begin-end
Assuming puts invalid in ensure
5. You want to open a file, write data, and always close it even if an error occurs. Which Ruby code correctly uses ensure for this cleanup?
hard
A. begin
file = File.open('data.txt', 'w')
file.write('Hello')
rescue
file.close
end
B. file = File.open('data.txt', 'w')
file.write('Hello')
file.close
C. file = File.open('data.txt', 'w')
begin
file.write('Hello')
ensure
file.close
end
D. begin
file = File.open('data.txt', 'w')
file.write('Hello')
ensure
file = nil
end
Solution
Step 1: Identify correct use of ensure for cleanup
file = File.open('data.txt', 'w')
begin
file.write('Hello')
ensure
file.close
end opens the file before begin, writes inside, and closes in ensure, guaranteeing closure.
Step 2: Check other options for errors
begin
file = File.open('data.txt', 'w')
file.write('Hello')
rescue
file.close
end closes in rescue, which only runs on errors, not always. file = File.open('data.txt', 'w')
file.write('Hello')
file.close doesn't handle errors. begin
file = File.open('data.txt', 'w')
file.write('Hello')
ensure
file = nil
end sets file to nil but doesn't close it.
Final Answer:
file = File.open('data.txt', 'w')
begin
file.write('Hello')
ensure
file.close
end -> Option C
Quick Check:
Ensure always closes file [OK]
Hint: Put cleanup like file.close inside ensure [OK]
Common Mistakes:
Closing file only in rescue block
Not closing file on error
Setting variable to nil instead of closing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.