From: Timothy Hunter Date: 2006-09-06T07:17:46+09:00 Subject: Re: How to store/load persistent data? Josef Wolf wrote: > It is clear to me that the ruby object is removed by the garbage > collector. But it is not clear what happens to other recources (a > TkCanvas in this case) allocated by this object. Check this out: > > #! /usr/bin/ruby > > require 'tk' > > root=TkRoot.new > > class Foo > def initialize > canvas = TkCanvas.new.pack > rect = TkcRectangle.new(canvas, 0, 0, 50, 50, "fill"=>"white") > end > end > > begin > x=Foo.new() > end > > GC.start > > # Object destroyed but canvas and rectangle are still alive > > Tk.mainloop > > I can't see a solution for this problem since I am a novice for ruby/OO/Tk. > How do you gurus handle such situations? > > There is a well-known Ruby idiom for coding block-scoped resources. There used to be a good page describing this in RubyGarden but alas that page seems to have disappeared. Anyway, here's the general example from that page: > def Resource.open( identifier ) # :yield: resource > resource = Resource.new( identifier ) > if block_given? > begin > yield resource > ensure > resource.close > end > else > return resource > end > end That is, create/open/whatever the resource is and yield to a block. Within the block use the resource. When the block returns, close/destroy the resource. The open method in the IO class is prototypical.