Exception handling: ensure
The ensure block is Ruby's equivalent of what is commonly named "finally" in other programming languages. It is used to define a section of code that will always be executed at the end of a block, regardless of whether an exception was raised.
The ensure block follows the same syntactical rules as rescue. That is, it can be inserted at the end of any method or block without requiring a corresponding begin statement. This also means you can have ensure without any rescue at all:
def safely_deal_with_file(file_path)
file = File.open(file_path, "r")
# Do something with the file
ensure
file&.close
end
const fs = require("node:fs");
function safelyDealWithFile(filePath) {
let file;
try {
file = fs.openSync(filePath, 'r');
// Do something with the file
} finally {
if (file) fs.closeSync(file);
}
}
See the signal to noise ratio difference in this side by side comparison!
I also love how well ensure pairs with the safe navigation operator &. to avoid nil-reference errors when closing the file, which saves us an explicit if check.
History
The ensure keyword was added together with the rest of Ruby's exception handling syntax in Ruby 1.6, released in 2000.