From: Dave Thomas <Dave / thomases.com>

> However, you're right - there is a bug in delete. If you delete two
> things, and the second has an index greater tahn the first, then it
> isn't deleted properly.
> 
> The fix is left as an exercise for the reader.

module AtExit
  @thingsToRun = {}
  @names = []
  
  def AtExit.run(name, &thing)
    AtExit.delete(name)
    @names.push(name)
    @thingsToRun[name] = thing
  end
  
  def AtExit.delete(name)
    @names.delete(name)
    @thingsToRun.delete(name)
  end
  
  def AtExit.runHandlers
    @names.reverse_each { |name| @thingsToRun[name].call }
 end
  
  at_exit { AtExit.runHandlers }
end

AtExit.run("goofy") { puts "Dave" }
AtExit.run("minnie") { puts "Says" }
AtExit.run("mickey") { puts "Regards" }
AtExit.delete("minnie")
AtExit.delete("mickey")

# =>

  Dave