Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is insert/delete on one array modifying another as well?

I have a question about using insert and delete_at with arrays. If I insert an element into an array (arry) and then store that value in a different variable (temp), why does the variable temp change after I use delete_at on arry? Is there a way to store the value of the array with the insert object permanently?

Here is some sample code:

arry = [0,1,3,4]
# => [0, 1, 3, 4]
arry.insert(1,5)
# => [0, 5, 1, 3, 4]
temp = arry
# => [0, 5, 1, 3, 4]
arry.delete_at(1)
# => 5
temp
# => [0, 1, 3, 4]
like image 467
CompChemist Avatar asked Feb 17 '23 05:02

CompChemist


1 Answers

When you assign an array to a new variable, the array itself is not copied but only reference to that array is set. If you want to save original array to new variable, you need to clone the array You can do it via dup.

temp = arry.dup
like image 58
emre nevayeshirazi Avatar answered Mar 05 '23 17:03

emre nevayeshirazi