From: David Alan Black Date: 2002-04-26T12:00:53+09:00 Subject: Re: how to check for unitialised class variable? Hello -- On Fri, 26 Apr 2002, Ian Macdonald wrote: > Hi, > > Observe the following: > > irb(main):006:0> class Foo > irb(main):007:1> def initialize > irb(main):008:2> @@foo ||= true > irb(main):009:2> end > irb(main):010:1> end > nil > irb(main):011:0> bar = Foo.new > NameError: uninitialized class variable @@foo in Foo > from (irb):8:in `initialize' > from (irb):11:in `new' > from (irb):11 > > The ||= (only assign if nil) assignment operator must necessarily > check for an existing value of @@foo and, if there isn't one, the > above error ensues. > > How should one rewrite the above code? The objective is to avoid > reassignment of @@foo, once it has been defined. I think I'm on safe ground here, because I'm cutting-and-pasting from ruby-talk:39007, by matz :-) Adapt as appropriate: def MyClass unless defined? @@myClassVar @@myClassVar = nil end end David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav