From: "David A. Black" Date: 2004-04-10T04:13:03+09:00 Subject: Re: Cache of objects Hi -- On Sat, 10 Apr 2004, rolo wrote: > -----Original Message----- > From: Joel VanderWerf [mailto:vjoel@PATH.Berkeley.EDU] > Sent: Friday, April 09, 2004 11:58 PM > To: ruby-talk ML > Subject: Re: Cache of objects > > > rolo wrote: > > class Thing > > @cache = {} > > def self.instance(name) > > @cache[name] ||= new(name) > > end > > def initialize(name) > > @name = name > > end > > end > > > > t1 = Thing.instance "t" > > t2 = Thing.instance "t" > > > > p t1.id > > p t2.id > > > > > > [rolo] mysterious. it works! but since cache is an instance level variable how is it shared amongst all the class instances? > > @cache is an instance variable of the class Object called Thing. It's > just a regular instance variable, but it happens to be stored in a class > object instead of in instances of the class. Instances of Thing can't > access it directly. > > [rolo] should it not be @@cache ? No, that's a class variable, which is different from an instance variable of a Class object. In spite of the shared use of '@', they're separate and different things. David -- David A. Black dblack@wobblini.net