From: Filipe Date: 2007-11-26T07:40:04+09:00 Subject: Re: Class variable as parameter On Nov 25, 11:50 am, Matt Todd wrote: > > >> On Nov 23, 2007, at 4:20 PM,Filipewrote: > > >>> I have the following situation: > > >>> class MyClass > > >>> def setVar(var,varValue) > > >>> var=varValue > > >>> end > > >>> def initialize > > >>> @myVar=0 > > >>> setVar(@myVar,1) > > >>> puts(@myVar.to_s) > > >>> end > > >>> end > > >>> test = MyClass.new > > >>> Unfortunately, this piece of code is returning 0 instead of the 1 I > > >>> would expect. Is there anything I could do? > > The most stylish, Ruby way to do what you are trying to do is as follows: > > class MyClass > > def initialize > @myVar1 = 0 # direct value manipulation > self.myVar1 = 1 # sent through your wrapper > puts @myVar1 > end > > def myVar1=(value) > @myVar1 = value > # process extra steps here > end > > end > > (Ehm, I should admit, there may be a better way to actually get the > accessor method to fire inside of initialize than self.myVar1, but > that's what I found to work.) I would still have to writer a myVar=(value) method for every single variable. That's what I'm trying to get rid of.