Vincent Stowbunenko wrote in post #1105954:
How do I make sure the first array stays original after the modification
of second array?
Variables in ruby hold references to objects. This can be evidenced by
viewing the object_ids:
irb:001> array1 = [1,2,3,4,5]
irb:002> array2 = array1
irb:003> array2.object_id
=> 70171269757120
irb:004> array1.object_id
=> 70171269757120
To de-duplicate the reference you need to create a second object, which
is a copy of the first. The simplest way is to use `dup`
irb:005> array2 = array1.dup
irb:006> array1.object_id
=> 70171269757120
irb:007> array2.object_id
=> 70171269775520
# ^^^^^
irb:008> array1.delete(1)
irb:009> array1
=> [2, 3, 4, 5]
irb:010> array2
=> [1, 2, 3, 4, 5]
The thing to remember is that Array#dup performs a shallow copy. For
example:
irb:011> array1 = [[1,2,3],[4,5]]
irb:012> array2 = array1.dup
irb:013> array1[0].delete(1)
irb:014> array1
=> [[2, 3], [4, 5]]
irb:015> array2
=> [[2, 3], [4, 5]]
The variables `array1` and `array2` point to different Array objects,
but each of _those_ independently maintains references to the _same_
inner-arrays. In other words, array1[0] and array2[0] both reference
the same object.
It's not only limited to arrays, either:
irb:016> array1 = ['a']
irb:017> array2 = array1.dup
irb:018> array1[0] << 'b'
irb:019> array1
=> ["ab"]
irb:020> array2
=> ["ab"]
There is no general-form solution to creating a deep-copy of a
datastructure in ruby.
···
--
Posted via http://www.ruby-forum.com/\.