Clone doesn’t clone the sub-objects that the main object refers to unless they are simple literals (like Integers). So for your second example, the array has references to the sub arrays and when it clones, it just clones the values of those references, but they still refer to the same arrays and when you change an index of the clones sub arrays, it changes the original ones.
···
—
Sent from Mailbox
On Wed, Nov 26, 2014 at 6:56 PM, mac <renkaiswpu@gmail.com> wrote:
Some problem with ruby clone, it is different between one-dimensional array and two-dimensional array.like below!
irb(main):001:0> arr_a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> arr_b = arr_a.clone
=> [1, 2, 3]
irb(main):003:0> arr_a.object_id == arr_b.object_id
=> false
irb(main):004:0> arr_b[0] = 4
=> 4
irb(main):005:0> arr_b
=> [4, 2, 3]
irb(main):006:0> arr_a
=> [1, 2, 3]
irb(main):007:0> arr_a = [[1,2,3],[4,5,6]]
=> [[1, 2, 3], [4, 5, 6]]
irb(main):008:0> arr_b = arr_a.clone
=> [[1, 2, 3], [4, 5, 6]]
irb(main):009:0> arr_a.object_id == arr_b.object_id
=> false
irb(main):010:0> arr_b[0][0] = 7
=> 7
irb(main):011:0> arr_b
=> [[7, 2, 3], [4, 5, 6]]
irb(main):012:0> arr_a
=> [[7, 2, 3], [4, 5, 6]]
one-dimensional not change original array, but two-dimensional change the original array!
why?