From: brabuhr@... Date: 2009-11-25T00:25:10+09:00 Subject: Re: Difference between << and += for Strings and Arrays. Bug? On Tue, Nov 24, 2009 at 9:46 AM, Pieter Hugo wrote: > Hi > I have been programming with Ruby for about 1 year and am loving it. I > cam across something that I can't figure out why it works the way it > does: > > Eg: > a=[1,2] > b=a > b << 3 > > The value of b is now [1,2,3], but the value of a is also [1,2,3]???? http://ruby-doc.org/core/classes/Array.html#M002167 "Append—Pushes the given object on to the end of this array." > And yet: > > a=[1,2] > b=a > b += [3] > > The value of b is still [1,2,3] but a remains [1,2]. This just doesnt > make sense to. The same happens with Strings. Why would the append > operator (<<) change the original variable, but other operators dont > seem to. http://ruby-doc.org/core/classes/Array.html#M002209 "Concatenation—Returns a new array built by concatenating the two arrays together to produce a third array." > PS What I really want to know is why the original variable is > changed at all? After b=a, the variables 'a' and 'b' both reference the same object. += creates a new array (the + part) and changes b to reference that new array (the = part). With << the object referenced by b is directly modified, it appears that a is also changed because a references the same object as b. It's not really that b was changed by <<, the object referenced by b is what changed.