Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inscrutable Ruby: Vector Assignment Example

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?

like image 310
JnBrymn Avatar asked Jan 27 '11 22:01

JnBrymn


1 Answers

In the first example you are creating a new array with the value [[0,1], 1]. Then you are reassigning a to refer to this array.

In the second example you are not creating a new array, nor are you changing what a refers 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:

a = [0, 1]  # Step 1
b = [a, 1]  # Step 2
a = b       # Step 3

In pictures it looks like this:

  • Step 1 - create an array:
---
|a|
---
 |
 v
 [0, 1]
  • Step 2 - create another array which includes a reference to the first:
    ---        ---
    |a|        |b| 
    ---        ---
     |          |
     |          v
     |          [ref, 1]
     |            |
     +------------+
     v 
     [0, 1]      
  • Step 3 - change a to 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 a still points to it. But now the first element in the array refers to the array itself.

like image 109
Mark Byers Avatar answered Sep 21 '22 00:09

Mark Byers