From: David Alan Black Date: 2004-04-08T12:24:18+09:00 Subject: Re: Preferred Instance Variable Access Method Hi -- Jean-Hugues ROBERT writes: > Hi, > > At 05:34 08/04/2004 +0900, you wrote: > What's the preferred way of accessing a class's instance variables? > > I tend to use @var instead of self.var (I guess var() would work, and > var too). > > I see two advantages: > 1) Faster (I never benchmarked however) > 2) Lines starting with @ are like methods with ! at the end => > Draw the attention to probable side effect on obj's state. Don't forget, though, that these techniques (@var vs. self.var) are only equivalent in certain simple (and common, but not unique) cases. If you're doing anything more complex, like: def var=(x) @var = x.to_s.upcase end then you don't have a choice; you have to go through the method (self.var = y) rather than just doing @var = y, elsewhere in the class. (The original question involved another level of remove (wrapping the attr_* methods themselves in "var_get" and "var_modify" methods, but wherever they occur, @var = and self.var= are not automatically equivalent.) This also points to a constraint on Eric's point about not wanting to worry about forgetting the 'self' -- namely, that you can only do that when you know for sure that #var= is a simple set method for @var. Also, the @var = y technique could come back to bite you if you reimplement the setter method and haven't routed your assignments through it: attr_accessor :var def initialize(y) @var = y # OK until you reimplement #var= to do something end # non-simple, at which point you have to remember # that you assigned directly to @var here. (I would have quoted Eric directly except I'm posting directly to comp.lang.ruby, because of the gateway problems, and Eric's posts don't seem to be making it here :-( David -- David A. Black dblack@wobblini.net