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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With