alert pay
alert pay

Reputation: 75

How to delete a element from two arrays independently which has been copied from one another?

a = [1,2,3]

=> [1, 2, 3]

b = a

=> [1, 2, 3]

b.delete(1)

=> 1

b

=> [2, 3]

a

=> [2, 3]

Array A has given [1,2,3] values, and Array A has been copied to Array B

Then whenever I delete a element from Array B , the element gets deleted from Array A too

eg : If i delete element 1 from array B ,it gets deleted from array A too..

How to avoid this, How to delete an element from these arrays separately ?

Upvotes: 1

Views: 68

Answers (2)

Coolness
Coolness

Reputation: 1992

You can use dup to create a copy of the array.

a = [1,2,3]
=> [1, 2, 3]
b = a.dup
=> [1, 2, 3]
a.delete(1)
=> 1
a
=> [2, 3]
b
=> [1, 2, 3]

EDIT:

As to why this is, when you assign b = a, you assign b to be a reference to a. This means that both variables refer the same underlying object. With dup we are forcing Ruby to create a copy of a.

Upvotes: 3

Innot Kauker
Innot Kauker

Reputation: 1373

You are creating a shallow copy in b, so the contents aren't copied. To copy them, use Object::clone: b = a.clone.

Upvotes: 0

Related Questions