From: Robert Klemme Date: 2004-10-13T00:44:35+09:00 Subject: Re: return val of initialize [WAS] Re: tempfiles created by tmpfile removed at exit - can I change this easily? schrieb im Newsbeitrag news:Pine.LNX.4.60.0410120828420.8667@harp.ngdc.noaa.gov... > On Tue, 12 Oct 2004, Robert Klemme wrote: > > >> require 'tempfile' > >> > >> class Tmpfile < Tempfile > >> class << self; attr :litter, true; end > >> def initialize(*a,&b) > >> t = super > >> ObjectSpace::undefine_finalizer self if self.class.litter > >> t > >> end > >> end > > > > What do you need that "t" for? IMHO it's completely superfluous. > > i always use a clearly defined return value in my code as, at minimum, > doccumentation. when i glance at the above it's instantly clear to me (eg. > when re-reading this in six months) that i am doing nothing except removing > the finalizer from the instance and returning it. Well, but since you don't know what Tempfile#initialize returns (it's not documented AFAIK) you can't deal with it properly anyway, can you? > in general i find that the > magic ruby rule of returning value of the last statement bad to rely upon in > all but the most simply cases - but for the real reason see below: > > > The return value of initialize is always completely ignored. > > that cannot be asserted: > > harp:~ > cat a.rb > class A > def initialize > 42 > end > def reinit > p initialize > end > end > > A::new.reinit > > harp:~ > ruby a.rb > 42 > > if you mean to say that 'the value of initialize is ignored by default for the > single case when it is called by the default Object#new method' then you are > correct. remember, initialize is simply a method called, in one single case, > to fill in blank objects - it's quite possible and acceptable to call it with > side effects from within the class, or from within subclasses. Didn't think of that. But still as #initialize's return value is generally *not* used I'd rather not rely on that value. In your example I'd have defined reinit like this - in concordance with your other statement about return values :-) def reinit initialize self end > in general i think it's poor practice to leave a method with a random return > value: one should return something meaningful and, if that's not possible, > return self to allow chaining. Totally agree! Otherwise some internal state / instance might leak that was never meant to be seen outside of the instance. > > Also from an aesthetical point of view, I'd expect the flag "litter" to > > behave exactly the other way round: if litter is true throw it away; you > > keep it if litter is true. > > tempfiles are thrown away 'properly' in the normal case - eg. they do not > 'litter' /tmp (a very dangerous practice). i would consider a program that > did not clean up after itself to have 'littered' - but it's of no matter: > change it if you like. Ah, ok *now* I understand how you meant it. Sorry for the noise. Kind regards robert