Alle Friday 05 December 2008, Hamza Haiken ha scritto:
Hi
Can someone explain to me why is this happening ?
>> matrix1 = ["One","Two","Three"]
=> ["One", "Two", "Three"]
>> matrix2 = matrix1
=> ["One", "Two", "Three"]
>> matrix2.shift
=> "One"
>> matrix2
=> ["Two", "Three"]
>> matrix1
=> ["Two", "Three"]
According to my logic, when I do matrix2.shift, it should have nothing
to do with matrix1. Why's this one shifted as well ?
Because matrix1 and matrix2 are only different names used to refer to the same
thing, as you can see by checking the values returned by matrix1.object_id and
matrix2.object_id. If you want the two variables to contain different objects,
you need to write
matrix2 = matrix1.dup
This will set the contents of matrix2 to a duplicate of matrix1, so that
changing one won't change the other. Note, however, that this is only a
shallow copy, that is: the array itself is duplicated, but its contents
aren't. This means that any method which changes one of the contained strings
in-place will affect both array. For example:
matrix2 = matrix1.dup
matrix1[0].sub!('O','o')
p matrix1
#=> ["one", "Two", "Three"]
p matrix2
#=> ["one", "Two", "Three"]
If you also need to be sure that the arrays contain different objects, you
need to do a deep copy, which can be achieved using marshal:
matrix2 = Marshal.load(Marshal.dump(matrix1))
I hope this helps
Stefano