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.
Ensure helps you run some code no matter what happens before. It is useful to clean up things like closing files or freeing resources.
begin # code that might fail ensure # cleanup code that always runs end
ensure block always runs after the begin block, even if there is an error.ensure to keep your program safe and clean up resources.begin puts "Doing work" ensure puts "Always runs" end
begin file = File.open("test.txt", "w") file.puts "Hello" ensure file.close if file end
This program shows that the ensure block runs even if an error is raised.
begin puts "Start task" raise "Oops, error happened" ensure puts "Cleanup: always runs" end
If an error happens, ensure still runs before the program stops or moves on.
Use ensure to avoid leaving files or connections open.
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.
ensure block in Ruby?ensureensure block runs code no matter what happens in the begin block, even if an error occurs.rescue which handles errors, ensure always runs for cleanup tasks.ensure = always runs cleanup [OK]ensure in Ruby?begin ... ensure ... end to guarantee cleanup code runs.rescue which is for error handling, not guaranteed cleanup.def test
begin
puts "Start"
raise "Error!"
ensure
puts "Cleanup"
end
end
testensure block runs next, printing "Cleanup".ensure, the error is not rescued, so it propagates and shows the RuntimeError message.ensure:
begin puts "Processing" # missing end for begin ensure puts "Cleaning up" end
begin block is missing its closing end before ensure.ensure must be inside the begin ... end block, so the missing end causes a syntax error.end for begin block -> Option Bensure for this cleanup?begin, writes inside, and closes in ensure, guaranteeing closure.Pass the test and this pattern moves unknown