"Stig Sandbeck Mathisen" <ssm / fnord.no> schrieb im Newsbeitrag news:90lekrj4kn4.fsf / talisker.nsc.no... > > I have a program that will create a lot of objects, mainly of type > SomeDocumentation::Host and SomeDocumentation::Role. > > Since the Role objects typically create a lot of Host objects, and the > other way around, I tried to be clever, and look up objects that > already exists with the same value of "name", since the initialize > reads a bit from disk. > > I've tried tried to solve it with the following code snippet: > > def initialize(name) > > ObjectSpace.each_object(self.class) do |anObject| > return anObject if anObject.name == name > end > > <do the real initialization, since we do not have an object with > the same .name attribute/method/whatever yet> > > end > > ...but when it is included in the Host initialize method, I end up > with a lot of empty Host objects for the second (third, fourth, and so > on) Role object when doing this from the main script: > > roles.uniq.each do |role| > aRole = SomeDocumentation::Role.new(role) > puts aRole.documentation > end > > Does anyone see what I'm doing wrong? > > -- > Sandbeck Mathisen - http://fnord.no > Trust the Computer, the Computer is your Friend 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"] Regards robert