From: "David A. Black" Date: 2004-04-08T05:53:12+09:00 Subject: Re: Preferred Instance Variable Access Method Hi -- On Thu, 8 Apr 2004, Bill Atkins wrote: > What's the preferred way of accessing a class's instance variables? > Almost every example I've seen uses the @ form: > > class Test > def var_set > @var = 3 > end > def var_modify(v) > @vare = 34 > return @var > end > end > > t = Test.new > t.var_set > puts t.var_modify > > The obvious problem with this can be seen in Test#var_modify. The > programmer meant to change the value of @var but made a typo and broke > his code. The program prints 3 instead of 34. > > The way around this is through accessors: > > class Test > attr_accessor :var > def var_set > self.var = 3 > end > def var_modify > self.vare = 34 > return self.var > end > end > > This produces an error that can be caught. > > My question is this: why is this form so rarely used? Is it the extra > typing? Is it somehow un-Rubyesque? It seems like a good way to > catch silly errors like the one above. I'm a little puzzled by your example.... Did you mean var_modify to take an argument? (It does in your first example, though the argument isn't used.) Assuming you do mean "def var_modify(v); self.var=v; end" .... That is indeed somewhat unidiomatic. From the point of view of the calling code, it's more idiomatic to do: obj.var = 100 than obj.var_modify(100) In fact it's so Rubyesque that Matz has provided the attr_* family of method-writing shortcuts :-) Wrapping them in further layers of set/get methods is redundant. As for the error -- there's no more or less danger here than in many other places where you use variable names. Consider this: def blah(x) y = 1 if x > 5 return y else return yy * 2 end end Of course yy is a typo, but you'll never know until you call the method with x <= 5. That (among other reasons) is why there's so much emphasis placed in the Ruby community on unit testing. David -- David A. Black dblack@wobblini.net