Andrew B
Andrew B

Reputation: 104

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]?

Upvotes: 0

Views: 78

Answers (3)

nPcomp
nPcomp

Reputation: 9943

array2 = array1.dup


array2 = array1.clone => Your changes effects both arrays

Upvotes: 1

Gagan Gami
Gagan Gami

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

Ursus
Ursus

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

Related Questions