Deep Copy in Ruby :
eg:
if a=1
b=a
a+=1
so, now a=2 and b= 1 which is very clear, right ?
again,
if a=[1,2,3]
b=a
a << 4 (just add an element into 'a')
so, now a=[1,2,3,4] and b = ?
can u guess ??? is that [1,2,3] ? no, its exactly [1,2,3,4] because the Array Object is not a POD(plain old data) type. The assignment operator doesn't make a copy of the value , it simply copies the reference to the array object. The a and b are now references to the same array object, any changes in either variable will be seen in the other.
eg:
if a=1
b=a
a+=1
so, now a=2 and b= 1 which is very clear, right ?
again,
if a=[1,2,3]
b=a
a << 4 (just add an element into 'a')
so, now a=[1,2,3,4] and b = ?
can u guess ??? is that [1,2,3] ? no, its exactly [1,2,3,4] because the Array Object is not a POD(plain old data) type. The assignment operator doesn't make a copy of the value , it simply copies the reference to the array object. The a and b are now references to the same array object, any changes in either variable will be seen in the other.
No comments:
Post a Comment