@dan rathbun said:
@tig said:
a1=[1,2,3]
both
a2=a1 ### makes a new reference to the same array, 'a1' a2=a1.to_a ### makes 'a1' into an array [which it is already!] and then makes a new reference to the same array, 'a1' !!
will still refer to a1, so consequently changing a2 changes a1 too !
BUT
a2=a1.dup
makes a separate copy of a1, as will
a2=a1+[] as adding two arrays together produces a new array, even when the second one is empty;
and now changing a2 leaves a1 alone
To clarify, since "assignment creates references"...:
a1=[1,2,3] ### creates a new array object referenced by a1
a2=a1 ### makes a new reference ( a2) to the same array object that a1 is pointing at.
a2=a1.to_a ### a1.to_a returns *self*
both references are pointing at the same array object, so consequently that object can be changed using either reference a2 or a1.
BUT
a2=a1.dup ### makes a new array object, (referenced by a2,) that is a copy of the array object that a1 is pointing at.
Nice round-up..
But be aware #dup performs a shallow copy. So any proper objects (as opposed to simple numbers) in that array are copied by reference.
So:
a = [10, 20, [30,31,32]]
c = a.dup
a[2][0] = 'Tada!'
c
will print:
[10, 20, ["Tada!", 31, 32]]