From: Louis J Scoras [mailto:[email protected]]
p array # Doh!! x = array ; x[1] = 'win!' p array # array has been changed
The thing to wrap your head around here is that ‘slots’ in an Array, and
the values in Hash objects, are very much like variables. They point to
values, they do not contain them.
So breaking down the above:
array = [ ‘you’, ‘lose’ ]
In this case there are three objects: the two strings, and the array.
The [0] and [1] slots in the array point to those two strings, floating
out in object space. The variable named ‘array’ is pointing the array
object floating in space.
a, b = array
Now, two new variables spring to live, each pointing to those floating
words. The code “foo = array[1]” is very much like the code “foo = bar”;
you’re asking Ruby to make the variable ‘foo’ point to whatever the
array slot/variable bar is pointing to. The ‘a’ and ‘b’ variables have
nothing to do with the array, except that they happen to be pointing at
the same objects in space.
b = ‘win’
Now you’ve just conjured into existence a new object (“win”), and told
the ‘b’ variable to point to it instead. The [1] slot of the array still
points at the “lose” object.
x = array
Here you’re saying “Hey Ruby, please, make the variable ‘x’ point to the
same thing as the variable ‘array’ is pointing at.”
x[1] = ‘win!’
Now you’ve made a new object (“win!”) and you’re saying to Ruby, “Hey,
you know the object that the ‘x’ variable is pointing at? Please ask its
[1] slot to point at this new “win!” object.”
Because ‘x’ and ‘array’ are both pointing at the same Array object
floating in space, and one of the slots of that array just changed, they
are both ‘updated’. (Nothing changes about ‘x’ or ‘array’, but when you
ask Ruby to inspect the object that either is pointing to, you see the
same result.)