Reputation: 104
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]
?
Upvotes: 0
Views: 78
Reputation: 9943
array2 = array1.dup
array2 = array1.clone
=> Your changes effects both arrays
Upvotes: 1
Reputation: 10251
I prefer Object#dup method, but here is one more option FYI:
> array1 = [1, 2, 3, 4]
#=> [1, 2, 3, 4]
> array2 = Array.new + array1
#=> [1, 2, 3, 4]
> array1.object_id
#=> 87422520
> array2.object_id
#=> 87400390
Upvotes: 0
Reputation: 30071
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
Upvotes: 4