From: Joel VanderWerf Date: 2004-11-13T06:20:15+09:00 Subject: Re: automatically call function on attribute set Joe Van Dyk wrote: > "Joel VanderWerf" wrote in message > news:4193C096.7070007@path.berkeley.edu... > >>Joe Van Dyk wrote: >> >>>Joel VanderWerf wrote: >>> >>> >>>> def fly >>>> self.x += 1 # don't use @x=, or else no >>>> notification end >>>> end >>>> >>> >>> >>>What is the difference between self.x and @x? >> >>In ruby, assigning to an instance variable @x like >> >> @x += 1 >> >>does not invoke any methods (except the + method of the Integer class, >>in this case). So there's no way for the Airplane class to detect the >>assignment and (in this case) notify observers. >> >>By contrast, the code >> >> self.x += 1 >> >>forces a call to the method "x=", which has been defined by "observable >>:x" to both set the value of @x and to notify observers. >> >>And just for completeness, the code >> >> x += 1 >> >>can only assign to a local variable, even if "x=" has been defined as a >>method. >> >> > > > Ok. In general, it's best to use self.x as opposed to @x? Depends. I tend to use @x as rarely as possible, so that subclasses can, if necessary, define methods that get/set the value in some other way. Or if I later decide that the class itself needs to do something else and not just go directly to the instance variable (for instance, logging code). But accessing @x is faster than sending the #x method to self.