"Nat Pryce" <nat.pryce / b13media.com> 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(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
puts "Left over objects:"
each_object(SimpleLog){|id| p id}


But when exec'ed, the finalizer is not invoked at all.

Any idea how to make this work?

TIA,
YS.