From: Rick DeNatale Date: 2008-05-12T00:01:42+09:00 Subject: Re: Sharing variables between classes and instances On Sun, May 11, 2008 at 8:33 AM, Leon Bogaert wrote: > David A. Black wrote: >> On Sun, 11 May 2008, Leon Bogaert wrote: >>> What I'm trying to achieve: add a variable to a class. Fill it with >>> data. Every nstance of that class should have access to the data in that >>> variable. But I want every instance be able to modify that variable, >>> without modifying the original value of the variable. >> I'm not sure what you mean exactly. Do you mean each instance should >> have a copy of the object? If so, I would just do: >> >> class Tester >> >> def self.vars >> @vars ||= [] >> end >> >> def self.add_var(var) >> self.vars << var >> end >> >> def vars >> @vars || self.class.vars >> end >> >> def add_var(var) >> @vars ||= self.class.vars.dup >> vars << var >> end >> end >> >> That gives the results you expect in your test. > Thanks David. That's a whole lot simpler. I think I'll stick with your > example. > Except I think I'll merge @vars & self.class.vars each time vars() gets > called. So you can update the original Tester class with new vars and > that the instances have access to these new vars too. You might also want to have a look at the class_inheritable_accessor and related methods from the activesupport gem (part of Rails), which never seems to come up in similar threads on Ruby talk. It sort of does what you want, although it sets things up when a class is subclassed and doesn't keep up with changes. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/