0
0
RubyHow-ToBeginner · 3 min read

How to Use ensure in Ruby: Syntax and Examples

In Ruby, ensure is used in a begin block to run code that must execute whether an error occurs or not. It guarantees that the code inside ensure always runs after the main block or rescue clauses finish.
📐

Syntax

The ensure block is placed after begin and optional rescue blocks. Code inside ensure always runs, no matter if an exception was raised or handled.

  • begin: Starts the block of code to run.
  • rescue: Handles exceptions if they occur.
  • ensure: Runs code that must always execute, like cleanup.
ruby
begin
  # code that might raise an error
rescue SomeError
  # code to handle the error
ensure
  # code that always runs
end
💻

Example

This example shows how ensure runs even if an error happens. It prints a message before and after the error, and the ensure block always runs.

ruby
begin
  puts "Start"
  raise "Oops!"
rescue
  puts "Error caught"
ensure
  puts "Always runs"
end
Output
Start Error caught Always runs
⚠️

Common Pitfalls

A common mistake is to think ensure runs only if there is an error. Actually, it runs every time, even if no error occurs. Also, code in ensure should not change the flow by returning values because it can override exceptions.

ruby
begin
  puts "No error here"
  # return "From begin"  # Avoid using return here in top-level code
ensure
  puts "Ensure runs"
  # Returning here would override the return above
  # return "From ensure"  # Avoid this
end
Output
No error here Ensure runs
📊

Quick Reference

KeywordPurpose
beginStart a block of code that might raise errors
rescueHandle specific errors if they occur
ensureRun code always, after begin and rescue blocks

Key Takeaways

Use ensure to run code that must execute no matter what happens in the block.
ensure runs after begin and rescue, even if no error occurs.
Avoid returning values inside ensure as it can override exceptions or other returns.
ensure is great for cleanup tasks like closing files or releasing resources.