From: Leon Bogaert Date: 2008-05-11T21:33:54+09:00 Subject: Re: Sharing variables between classes and instances David A. Black wrote: > Hi -- > > On Sun, 11 May 2008, Leon Bogaert wrote: > >> Hi all, >> >> 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. > > > David 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. Thanks! -- Posted via http://www.ruby-forum.com/.