Consider the following:
a=[0,1] #our starting value
a=[a,1] #=> [[0,1],1] as expected
I would anticipate the following to have the same result:
a=[0,1] #same starting place
a[0]=a #should make a the same thing as it was above, right?
a #=> [[...],1] !!!
In the first example, the second assignment refers to the value of a before the assignment was made. In the second example, the second assignment performs a recursive assignment. This feels like different behavior to me. Is this behavior in fact consistent? If so can someone please explain why?
In the first example you are creating a new array with the value [[0,1], 1]. Then you are reassigning
ato refer to this array.In the second example you are not creating a new array, nor are you changing what
arefers to. You are changing the existing array to contain a reference to itself. That’s very different.More details
The first example is roughly equivalent to this code:
In pictures it looks like this:
--- --- |a| |b| --- --- | | | v | [ref, 1] | | +------------+ v [0, 1]ato point to the array created in step 2:--- --- |a| |b| --- --- | | +----------+ v [ref, 1] | +-------------+ v [0, 1]On the other hand, the code in the second example gives you this:
--- |a| --- | +---+ | v | [ref, 1] | | +-----+Here there is still only one array, and
astill points to it. But now the first element in the array refers to the array itself.