On Tue, 2006-02-28 at 21:03 +0900, Minkoo S. wrote:
chiaro scuro wrote:
However, when you use it on the left handside you must
prefix with self, otherwise ruby thinks it is a variable n, rather
than a call to the attribute writer ‘n=’.
It is strange because
n=1 is fine, but
n -= 1 is not.
Well, n = 1 just assigns the fixnum 1 to a (new) local variable ‘n’.
n -= 1 is expanded to n = n + 1.
Normally, n + 1 would end up calling your method because Ruby would have
to figure out whether it’s a method or variable, but because in this
case Ruby has seen a bare assignment to ‘n’ by that point, it remembers
that and assumes ‘n’ is a local variable.
This local variable isn’t yet initialized (the n + 1 would be it’s
initializer), so n + 1 ends up being nil + 1, or (effectively) nil.+(1),
hence the “undefined method ‘+’ for nil:NilClass”.
Using self.n = 1 forces Ruby to treat the assignment as involving the
method ‘n’ on ‘self’.
I don’t think it’s a bug, but I know it’s tripped people (including me)
up before. From the implementation point of view it’s probably the
lesser of two evils, though.