From: Robert Klemme Date: 2004-03-24T16:54:28+09:00 Subject: Re: How to avoid duplicate object creations? "Stig Sandbeck Mathisen" schrieb im Newsbeitrag news:90lad274i50.fsf@talisker.nsc.no... > "Robert Klemme" writes: > > > module SomeDocumentation > > class Named > > attr :name > > > > def initialize(name) > > @name = name > > end > > end > > > > class Host < Named > > INSTANCES = Hash.new {|h,name| h[name] = self.new(name) } > > end > > > > class Role < Named > > INSTANCES = Hash.new {|h,name| h[name] = self.new(name) } > > end > > end > > > > SomeDocumentation::Host::INSTANCES["foo"] > > SomeDocumentation::Role::INSTANCES["foo"] > > Brilliant, thank you. I think I need to study it for a while, to see > exactly what it does in combination with my code, though. :) > > In addition to this, I also got a message outside the newsgroup > telling me to use a @@instances hash in the classes, which seems to be > about the same solution. I would not choose class variables in this case. First, you want scoping by class and not through a hierarchy. If Host and Role somehow derive from each other then you have to choose a more comples hash key (i.e. pair of class and name) to ensure that you don't mix up stuff. The other is a bit more personal: I generally try to prevent the usage of class variables since their usage can lead to unexpected results as well as subtle errors. One thing is that order matters in which a class var is referenced. Try this: #!/usr/bin/ruby def t(cl) p [cl, cl.new.test] end # ------------------ class Base1 (@@foo ||= []) << "base1" def test; @@foo; end end class Derived1 < Base1 (@@foo ||= []) << "derived1" end # ------------------ class Base2 def test; @@foo; end end class Derived2 < Base2 (@@foo ||= []) << "derived2" end class Base2 (@@foo ||= []) << "base2" end # ------------------ class Base3 end class Derived3 < Base3 (@@foo ||= []) << "derived3" def test; @@foo; end end class Base3 (@@foo ||= []) << "base3" def test; @@foo; end end # ------------------ t Base1 t Derived1 t Base2 t Derived2 t Base3 t Derived3 Regards robert