0
0
Rubyprogramming~5 mins

Ensure for cleanup in Ruby

Choose your learning style9 modes available
Introduction

Ensure helps you run some code no matter what happens before. It is useful to clean up things like closing files or freeing resources.

You open a file and want to make sure it closes even if an error happens.
You start a network connection and want to close it no matter what.
You allocate memory or resources and want to release them safely.
You want to print a message or log something after a block of code runs, even if it fails.
Syntax
Ruby
begin
  # code that might fail
ensure
  # cleanup code that always runs
end
The ensure block always runs after the begin block, even if there is an error.
Use ensure to keep your program safe and clean up resources.
Examples
This prints both lines no matter what.
Ruby
begin
  puts "Doing work"
ensure
  puts "Always runs"
end
This opens a file and makes sure it closes even if writing fails.
Ruby
begin
  file = File.open("test.txt", "w")
  file.puts "Hello"
ensure
  file.close if file
end
Sample Program

This program shows that the ensure block runs even if an error is raised.

Ruby
begin
  puts "Start task"
  raise "Oops, error happened"
ensure
  puts "Cleanup: always runs"
end
OutputSuccess
Important Notes

If an error happens, ensure still runs before the program stops or moves on.

Use ensure to avoid leaving files or connections open.

Summary

Ensure runs code no matter what, for cleanup.

It helps keep your program safe and resources free.

Use it after begin blocks to guarantee cleanup.