From: Rick DeNatale Date: 2009-11-25T00:22:11+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]???? > 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. PS What I really want to know is why the original variable is > changed at all? This is another example of the classic confusion between variables and objects. variables only reference objects, the aren't objects themselves a = [1, 2] a.object_id # => 2148166040 b = a b.object_id # => 2148166040 b << 3 b.object_id # => 2148166040 a # => [1, 2, 3] b # => [1, 2, 3] b += [4] a # => [1, 2, 3] b # => [1, 2, 3, 4] a.object_id # => 2148166040 b.object_id # => 2148162660 a<< whatever sends the << message to the object referenced by a, which changes the object. This change will be visible no matter which variable referencing the object The assignment operator changes the binding of the variable on the left hand side so that it references the object which is the result of evaluating the right hand side. And x += y is the same as x = x + y So in the b += [3] case The variable b is changed to reference a new object which is the result of b + [3] HTH. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale