Kernel#at_exit

at_exit { block }
Returns: Proc · Updated March 13, 2026 · Kernel Methods
exit hooks lifecycle cleanup

at_exit registers a block of code that Ruby will execute when the program terminates. The registered blocks run in reverse order of registration, after all other Ruby code has finished. This is useful for cleanup tasks like closing file handles, flushing buffers, or logging shutdown events.

Syntax

at_exit { block }

Parameters

at_exit takes no named parameters—it only accepts a block.

Examples

Basic usage

at_exit { puts "Program is shutting down..." }

puts "Running main program..."
# Running main program...
# Program is shutting down...

Multiple at_exit handlers

at_exit { puts "First handler" }
at_exit { puts "Second handler" }
at_exit { puts "Third handler" }

# Output:
# Third handler
# Second handler
# First handler

Cleanup with file handles

log_file = File.open('application.log', 'a')

at_exit do
  log_file.puts "[\#{Time.now}] Application terminated"
  log_file.close
end

puts "Logging startup..."
# Logging startup...

Common Patterns

Graceful shutdown handlers: Register cleanup code that must run regardless of how the program exits.

at_exit do
  puts "Final cleanup complete"
end

Order matters: Multiple at_exit blocks run in LIFO order. Register critical handlers first.

See Also