From: Ned Konz Date: 2002-05-26T09:04:43+09:00 Subject: Re: Stymied by Ruby's garbage collector On Saturday 25 May 2002 01:22 pm, Yohanes Santoso wrote: > 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 Part of the problem is that your create_finalizer is an instance method. Which means that self is the object itself. Which also means that the closure has a reference to self. It instead should probably be a class method. As far as how to find the logfile, you can just pass it in to the create_finalizer: ObjectSpace.define_finalizer(self, SimpleLog.create_finalizer(@logfile)) def SimpleLog.create_finalizer(logfile) proc {|id| $stderr.puts("finalizer on #{id}") logfile.puts "closed properly" logfile.close } end -- Ned Konz http://bike-nomad.com GPG key ID: BEEA7EFE