I'm having some confusion about populating a new array with an existing array. It seems like if I set one array equal to the other, they become dynamically linked for the rest of the code. Is this a compiler attribute or am I not using the correct functions to store the values of one array in another? I hope this isn't an extremely basic question.
main_arr = [1, 2, 3, 4, 5]
temp_arr = main_arr
puts "Main: " + main_arr.to_s
puts "Temp: " + temp_arr.to_s
main_arr.clear
puts "Main: " + main_arr.to_s
puts "Temp: " + temp_arr.to_s
Output:
Main: [1, 2, 3, 4, 5]
Temp: [1, 2, 3, 4, 5]
Main: []
Temp: []
ais your array,a.dupwill create a "shallow" copy. Suppose, for example,a = [[1,2], [3,4]]. Thenb = a.dup #=> [[1, 2], [3, 4]]. So far, so good. Now lets add an element tob:b << 'dog' #=> [[1, 2], [3, 4], "dog"].ais unchanged:a #=> [[1,2], [3,4]]. Considerb[1][0] #=> 3. Now let's change that element ofband see what happens toa:b[1][0] = 'cat'; b #=> [[1, 2], ["cat", 4], "dog"]; a #=> [[1, 2], ["cat", 4]]. Not what you were expecting? That's becausedupcreates a "shallow" copy ofa.