In ``[ruby-talk:18256] Init & "shutdown"'', Ryan Tarpine <rtarpine / hotmail.com> said: > I'm trying to write a ruby extension that needs to run a init() function > ONLY the first time a certain class is instantiated, and a shutdown() ONLY > the last object is destroyed. How can I do this? The init() half seems > easier, with something like (in ruby code, would be C) What is ``the last object''? (1) No more object exists when GC. (2) The user will not make no more object. Anyway, ObjectSpace::define_object_finalizer may be a solution: class Foo def Foo::shutdown puts("Ahhhhhh") end def initialize ObjectBook::checkin(self, :shutdown) end end module ObjectBook POOL = {} def self::checkin(obj, mid) Thread::critical = true klass = obj.type key = obj.id POOL[klass] ||= [] POOL[klass].push(key) ObjectSpace::define_finalizer(obj, checkout(klass, key, mid)) Thread::critical = false end def self::checkout(klass, key, meth) proc do Thread::critical = true if POOL[klass].size == 1 POOL[klass].shift klass.__send__(meth) else POOL[klass].delete(key) end Thread::critical = false end end end p Foo.new p Foo.new GC.start p "--------" p Foo.new p Foo.new -- Gotoken