From: Joel VanderWerf Date: 2006-10-26T14:39:17+09:00 Subject: Re: Popularity Contest: Initializing Class-Level Instance Variables Phrogz wrote: > TECHNIQUE 2 - ON-DEMAND TEST/INITIALIZATION > ------------------------------------------- > class Alpha > def self.m1; (@foo||=[]) << rand; end > def self.m2; (@foo||=[]).map{ rand }; end > end > > class Bravo < Alpha > # Nothing special here > end I prefer a variant of the above: class Alpha def foo @foo ||= [] end def self.m1; foo << rand; end def self.m2; foo.map{ rand }; end # note that the expression for contstructing foo is not # repeated twice end class Bravo < Alpha # Nothing special here end class Charlie < Alpha def foo @foo ||= Set.new # or some other collection class end # This implies that all _subclasses_ of Charlie will # (unless overridden) use a set for the #foo method end class Delta < Charlie # default to Charlie's choice of Set as the foo collection end class Echo < Alpha def initialize(*) super @foo = [1,2,3] # possible to specify in advance end end -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407