From: Robert Klemme Date: 2011-10-05T00:58:46+09:00 Subject: Re: Operator Overloading On Tue, Oct 4, 2011 at 5:52 PM, Dave Aronson wrote: > On Tue, Oct 4, 2011 at 10:03, Brian Candler wrote: > >> (Of course, 'x' and 'self.x' are the same; you can write 'self.x' if you >> think it's clearer) > > Not quite.  This is one of Ruby's little gotchas.  A naked "x" will be > taken as a local variable in the method.  If you want to use an > instance variable you *must* precede it with either "self." or "@". The story is a bit more complex. 1. writing "x = exp" will _always_ assign to a local variable. If you want to invoke the setter method you _must_ do "self.x = expr". 2. reading "x" will access a local variable if it is defined and fall back to the getter method if there is no variable. "self.x" will always invoke the getter method regardless whether there is a local variable or not. Example: $ ruby19 -e 'def x;1;end;public :x;def f;p x, self.x;x=99;p x, self.x;end;f' 1 1 99 1 Needless to say that it's not the best of practices to mix local variables and properties of the same name. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/