From: Phrogz Date: 2006-10-26T13:50:06+09:00 Subject: Popularity Contest: Initializing Class-Level Instance Variables Subclassing a class that uses class-level instance variables requires that you initialize them for subclasses. Which of the following three techniques do you prefer? TECHNIQUE 1 - EXPLICIT INITIALIZATION ------------------------------------- class Alpha @foo = [] def self.m1; @foo << rand; end def self.m2; @foo.map{ rand }; end end class Bravo < Alpha @foo = [] end 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 TECHNIQUE 3 - PARENT CLASS HANDLES FOR SUB-CLASSES -------------------------------------------------- class Alpha @foo = [] def self.m1; @foo << rand; end def self.m2; @foo.map{ rand }; end def self.inherited(subklass) subklass.instance_eval{ @foo=[] } end end class Bravo < Alpha # Nothing special here end