1

I tried to solve a kata today that took me through a loop through one portion of the exercise. The problem I experienced can be simplified to the following nuance:

node = [1]
root_node = node

node << 2

p node #[1,2]
p root_node #[1,2]

node = 1
root_node = node

new_node = 3
node = new_node


p node #3
p root_node #1

Why is it that node and root_node both change when I modify the array assigned to one variable but assigning values to a variable doesn't modify the other?

I would have expected node = [1,2] and root_node = [1].

Could someone shed light onto this or direct me towards documentation regarding this. I don't think I ever noticed that that was the case. Thank you.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Dan Rubio
  • 4,709
  • 10
  • 49
  • 106
  • `<<` changes the object the variable is referring to whereas `=` changes the variable itself. If two variables refer to the same object (like in the first example) and you change that object, the change is reflected by both variables. – Stefan Sep 24 '19 at 19:10
  • you probably wanted to do `root_node = node.dup` in your second line. – Adobe Sep 24 '19 at 19:29

1 Answers1

1

When you assign an array, the variable holds a value of a reference to this array. When you assign this to another variable, the reference is copied. Then when you call << mutating the array, it's visible under both variables, because there is only one array.

When you assign an integer, the a value of this integer is stored in the variable. When you reassign it, another value is stored in this variable. There is no difference if you reassign it using a constant a = 1 or another variable a = b.

An important thing to note is that assignment works this way also for arrays - the value of the reference is reassigned. If you assign another array, the original one is not changed.

node = [1]
root_node = node
new_node = [3]
node = new_node
p node
#[3]
p root_node
#[1]

See also:

mrzasa
  • 22,895
  • 11
  • 56
  • 94