From: "Ara.T.Howard" Date: 2003-11-29T08:27:12+09:00 Subject: Re: selfassignment and close On Fri, 28 Nov 2003, Simon Strandgaard wrote: > Date: Fri, 28 Nov 2003 20:24:58 +0100 > From: Simon Strandgaard > Newsgroups: comp.lang.ruby > Subject: selfassignment and close > > I would like to overload the '+=' operator. But it doesn't seems to be > possible? If it isn't possible, then how to use the '+' operator and at > the same time get the instance #closed correctly ? > > > server> ruby a.rb > open 42 > open 43 > close 42 > close 43 > ----------------------- > open 42 > open 43 > close 43 > server> expand -t2 a.rb > class Iterator > def initialize(value) > @value = value > puts "open #{@value}" > end > def close > puts "close #{@value}" > end > def +(n) > self.class.new(@value + n) > end > end > > a = Iterator.new(42) > b = a + 1 > a.close > b.close > > puts "-----------------------" > > a = Iterator.new(42) > a += 1 # Question: How to do selfassignment ? > a.close > # 42 never gets closed! > server> something like this: class Iterator class << self def objs; @objs ||= []; end def reap; objs.each{|obj| obj.close}; end def new(*args,&block); objs << (obj = super); obj; end at_exit { Iterator.reap } end def initialize(value) @value = value puts "open #{@value}" end def close puts "close #{@value}" unless @closed @closed = true end def +(n) self.class.new(@value + n) end end #a = Iterator.new(42) #b = a + 1 #a.close #b.close puts "-----------------------" a = Iterator.new(42) a += 1 # Question: How to do selfassignment ? a.close # 42 never gets closed! if you rely on ObjectSpace.define_finalizer you don't really know when the call will be made, but perhaps something using it would be better... this would cause an apparent 'leak' in long running programs. the general idea - track objects within the class itself and make sure to free them - should be workable for you though. food for thought... -a -- ATTN: please update your address books with address below! =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | STP :: http://www.ngdc.noaa.gov/stp/ | NGDC :: http://www.ngdc.noaa.gov/ | NESDIS :: http://www.nesdis.noaa.gov/ | NOAA :: http://www.noaa.gov/ | US DOC :: http://www.commerce.gov/ | | The difference between art and science is that science is what we | understand well enough to explain to a computer. | Art is everything else. | -- Donald Knuth, "Discover" | | /bin/sh -c 'for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done' ===============================================================================