Austin Ziegler
3/31/2006 8:54:00 PM
On 3/28/06, ara.t.howard@noaa.gov <ara.t.howard@noaa.gov> wrote:> On Wed, 29 Mar 2006, Justin Bailey wrote:> > A cheap just-in-time initialization trick is the "||=" trick:> >> > def add_name(n)> > @name ||= Array.new> > @name << n> > end> >> > Now, how would you do the opposite of this pattern? More specifically, what> > kind of construct would evaluate to a true value once, and then nil from> > then on? I came upon this in the context of for loops, where I want a> > one-time "starting" value to be present the first time through the loop,> > then nil. And I wanted to do it in a cool way - i.e. not just assign the> > value to nil at the end of the loop, though of course that is the easiest> > way.> harp:~ > ruby -e' 3.times{ p( @x ? nil : @x=42) } '> 42> nil> nilruby -e'first = true; 3.times { p first &&= nil }'The opposite of ||= is &&=; it may not be appropriate for therequested purpose, though. It allows for a "change only if set" sortof test. I think I've used it *once*.-austin--Austin Ziegler * halostatue@gmail.com * Alternate: austin@halostatue.ca