From: Yohanes Santoso Date: 2002-05-26T05:22:19+09:00 Subject: Re: Stymied by Ruby's garbage collector "Nat Pryce" writes: > This is a common complaint from people used to C++ or Java, probably because > they are not used to a language with proper closures. This page on the Ruby > Garden wiki explains how to use finalisers to clean up an object's private > state: > I read the discussion page you referred to at http://www.rubygarden.org/ruby?DiscussionOnUsingFinalizers But I'm having difficulty in not keeping a reference to the gc'd object class SimpleLog def initialize(where) @logfile = File.new(where, "w+") ObjectSpace.define_finalizer(@logfile, create_finalizer) ObjectSpace.define_finalizer(self, create_finalizer) end def write(msg) @logfile.puts msg end def create_finalizer logfile = @logfile proc {|id| puts "Finalizer on #{id}" #now how do I close logfile without #a reference to it? logfile.puts "Closed properly" logfile.close } end end include ObjectSpace a = SimpleLog.new("/tmp/aaa") a.write("HI") a = nil # release ref to instance of SimpleLog. garbage_collect #should gc'd the SimpleLog instance each_object(SimpleLog){|id| p id} When execed from irb, garbage_collect does not collect the instance, and the finalizer is called when exiting irb. Even then, there is no