From: Brian Candler Date: 2002-10-12T20:56:37+09:00 Subject: Re: Things That Newcomers to Ruby Should Know On Sat, Oct 12, 2002 at 01:05:26AM +0900, Kontra, Gergely wrote: > >3) 'x+=b', 'x*=b' and other assignment operators is internally translated > >into 'x=x+b' and so on, so these operators assign to x reference to > >newly created object > > If this is true, a+=1 creates a new object. Can't it be avoided? If I understand my maths correctly: numbers always exist, they are neither created nor destroyed :-) Actually, a=1 # a is a reference to the number 1 (object of class Fixnum) a+=1 # a is now a reference to the number 2 However in practise this is efficient, since there appears to be a very compact internal representation of references to Fixnums: irb(main):001:0> 0.id 1 irb(main):002:0> 1.id 3 irb(main):003:0> 2.id 5 So I don't think that an object representing "the number 2" is actually allocated on the heap, thankfully :-) Hence "a+=1" does not increment the object pointed to by 'a' (you can't increment the number 1, it's meaningless); rather, 'a' is changed to reference a new object which is the result of applying method +(1) to the original object. If 'a' references any other type of object, then 'a+=1 creates a new object' is surely the desired behaviour? a += 1 is shorthand for a = a + 1 which is shorthand for a = a.+(1) and in the general case you can't say that the method '+' when applied to the object referred to by 'a' returns an object of the same class - and even if it does, changing the original object in-situ is probably not what you want anyway. For example: a="fred" b=a a+=" flintstone" leaves 'b' pointing to the original string object ("fred") whilst 'a' references to a new object. Regards, Brian.