Andrew B Andrew B - 1 year ago 47
Ruby Question

How can I modify an array without destroying an array assigned to it?

Consider the following:

array1 = [1, 2, 3, 4]
array2 = array1 # => [1, 2, 3, 4]
array2.pop
array2 # => [1, 2, 3]
array1 # => [1, 2, 3]


Why is
array1
destroyed when I've only called
pop
on
array2
? Is there a way to
pop
the last value from
array2
and leave
array1
intact so that I get
array1 # => [1, 2, 3, 4]
?

Answer Source

It's an aliasing issue. Your references point to the same Array object in memory. If your arrays contain simple Integers like those dup method do the trick.

array2 = array1.dup
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download