From: Tom Stuart Date: 2009-11-25T00:26:02+09:00 Subject: Re: Difference between << and += for Strings and Arrays. Bug? 2009/11/24 Pieter Hugo : > Hi 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]???? b=a means 'the variable b points to the same object as the variable a'. So calling a method on b which changes the underlying object means that the underlying object is changed, regardless of whether you call it a or b. The << method changes the array. As the docs describe it: "Append—Pushes the given object on to the end of this array." (http://ruby-doc.org/core/classes/Array.html#M002167). > 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. 'b += [3]' is syntactic sugar, or shorthand, for 'b = b + [3]'. i.e. This calls the '+' method on b 'under the hood'. '+' does not change the array, but returns a new array. From the docs again: "Concatenation—Returns a new array built by concatenating the two arrays together to produce a third array." (http://ruby-doc.org/core/classes/Array.html#M002209). So here you're getting a completely separate object and saying that the variable b should point to this new object. The old object pointed to by b (and also by a) is unaffected. > The same happens with Strings. As per the docs for Strings on the equivalent methods. > Why would the append > operator (<<) change the original variable, but other operators dont > seem to. PS What I really want to know is why the original variable is > changed at all? I hope my explanations make some kind of sense and help answer these questions? Cheers, Tom