1

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 ?

alert pay
  • 75
  • 6

2 Answers2

3

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.

Coolness
  • 1,932
  • 13
  • 25
0

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

Innot Kauker
  • 1,333
  • 1
  • 18
  • 30