Re: Subclassing Struct.new
by Ross Bamford other posts by this author
Feb 28 2006 4:29AM messages near this date
Re: Subclassing Struct.new
|
Re: Subclassing Struct.new
On Tue, 2006-02-28 at 21:03 +0900, Minkoo Seo 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.
--
Ross Bamford - rosco@roscopeco.REMOVE.co.uk
Thread:
Minkoo Seo
Chiaro Scuro
Minkoo Seo
Yukihiro Matsumoto
Mark Wilden
Markus Werner
Chiaro Scuro
Minkoo Seo
Minkoo Seo
Hal Fulton
mental
Ross Bamford
mental
Ross Bamford
Chiaro Scuro
Ross Bamford
Chiaro Scuro
Minkoo Seo
Chiaro Scuro
mental
Chiaro Scuro
mental
Yukihiro Matsumoto
Caleb Clausen
Yukihiro Matsumoto
Caleb Clausen
MenTaLguY
Yukihiro Matsumoto
gwtmp01
Chiaro Scuro
mental
Chiaro Scuro
mental
Logan Capaldo
Pit Capitain
|