From: "Florian Groß" Date: 2005-06-18T09:56:00+09:00 Subject: Re: Why do arrays work this way? Nigel Wilkinson wrote: > irb(main):058:0> a=[1,2,3,4,5]; b = a; b[3] = 'w'; a > => [1, 2, 3, "w", 5] > > so what's the logic behind 'a' & 'c' changing when I change 'b'. > > Is this a bug? and if not what's the reasoning behind this behaviour > please. In Ruby variables are just names for objects. If you do my_array = [1, 2, 3] you name an array with the elements 1, 2 and 3 as my_array. If you then do my_numbers = my_array you just give the object named my_array another name (my_numbers). So what you did was just variable aliasing and nothing else. Please note that in Ruby var += 5 is exactly the same as var = var + 5 which binds another name to the variable. This means that a = 5 b = a b += 1 [a, b] # => [5, 6] because the objects didn't change at all -- you just decided to rename things. Other languages with value semantics typically create a copy of the original object when you assign them to anything. This is typically done in Ruby like my_array = [1, 2, 3] my_copy = my_array.clone which will then give you the behavior you intended: my_array[0] = :changed my_array # => [:changed, 2, 3] my_copy # => [1, 2, 3] I think that Ruby's behavior is correct because languages where you explicitly have to specify that you want a reference to an object instead of a copy of it (like PHP used to do it even for values that are typically automatically passed by reference in the traditional languages like C++ and Java) cause more confusion. In Ruby you just give names to objects and ask them for a copy when you want one. It takes a short introduction (simply because languages that use pass-by-value somewhere are more common), but leads to less trouble later.