ensure runs cleanup-style code after a protected operation succeeds or fails.

ensure An `ensure` clause runs after the `begin` body and any matching `rescue`.

Ensure Clause

mode
ensure_clause.rb
Replay: real traced execution (multi-file project)
mode = "ok"
status = "starting"

begin
  status = "working"
  raise "temporary failure" if mode == "fail"
  status = "finished"
  puts "status=#{status}"
rescue RuntimeError
  status = "rescued"
  puts "status=#{status}"
ensure
  puts "ensure=ran"
end

puts "mode=#{mode}"
mode = "fail"
status = "starting"

begin
  status = "working"
  raise "temporary failure" if mode == "fail"
  status = "finished"
  puts "status=#{status}"
rescue RuntimeError
  status = "rescued"
  puts "status=#{status}"
ensure
  puts "ensure=ran"
end

puts "mode=#{mode}"
mode = "retry"
status = "starting"

begin
  status = "working"
  raise "temporary failure" if mode == "fail"
  status = "finished"
  puts "status=#{status}"
rescue RuntimeError
  status = "rescued"
  puts "status=#{status}"
ensure
  puts "ensure=ran"
end

puts "mode=#{mode}"
  1. mode ← ok, status ← starting

    1mode→ ok = "ok"  #@mode="fail", "retry"2status→ starting = "starting"34begin5  status→ working = "working"6  raise "temporary failure" if mode == "fail"7  status→ finished = "finished"8  puts "status=#{statusfinished}"9rescue RuntimeError10  status = "rescued"11  puts "status=#{status}"12ensure13  puts "ensure=ran"14end1516puts "mode=#{modeok}"
    outputstatus=finished
    ensure=ran
    mode=ok
  1. mode ← fail, status ← starting

    1mode→ fail = "fail"2status→ starting = "starting"34begin5  status→ working = "working"6  raise "temporary failure" if mode == "fail"7  status = "finished"8  puts "status=#{status}"9rescue RuntimeError10  status→ rescued = "rescued"11  puts "status=#{statusrescued}"12ensure13  puts "ensure=ran"14end1516puts "mode=#{modefail}"
    outputstatus=rescued
    ensure=ran
    mode=fail
  1. mode ← retry, status ← starting

    1mode→ retry = "retry"2status→ starting = "starting"34begin5  status→ working = "working"6  raise "temporary failure" if mode == "fail"7  status→ finished = "finished"8  puts "status=#{statusfinished}"9rescue RuntimeError10  status = "rescued"11  puts "status=#{status}"12ensure13  puts "ensure=ran"14end1516puts "mode=#{moderetry}"
    outputstatus=finished
    ensure=ran
    mode=retry