thehoooplehead thehoooplehead - 2 months ago 12
Ruby Question

Set an array equal to another, then change the first array without affecting the second

I have an array 'a' and I later set a new array 'b' equal to 'a'. When I remove an element from either array, they both change rather than the explicitly referenced array. I think this is because they're pointing to the same underlying object?

a= ["cat","hat","dog"]
b= a
a.delete_at(0)
print a
>> a = ["hat","dog"
print b
>> b = ["hat","dog"]


How can I set two variables equal but allow them to be independent for later operations? I'm looking for behaviour like this:

a= ["cat","hat","dog"]
b= a
a.delete_at(0)
print a
>> a = ["hat","dog"
print b
>> b = ["cat","hat","dog"]

Answer

Use Object#dup to create a duplicate of the original array:

a = ["cat","hat","dog"]
b = a.dup # b now points to a duplicate of a, not a itself

b # => ["cat","hat","dog"]
b.delete_at(0)

b # => ["hat","dog"]
a # => ["cat","hat","dog"]

To verify this behavior:

a = [1, 2, 3]
b = a
a.object_id == b.object_id # => true, a and b point to the same objects

a = [1, 2, 3]
b = a.dup
a.object_id == b.object_id # => false, a and b point to different objects