a=[1,2],[]]
b = Array.new(a)
b[1].push(b[0].pop)
I want to change a to before and after b to
Both become [[1], [2]]
My mistake? Ruby's mistake?
Quoted from Array.new
Replicates and returns the specified array ary. This is a shallow replication that does not replicate elements like Array#dup.
Therefore, the element created in Array.new is the same as the original object (referred to the same object).
So-called shallow copy (shallow copy).
Browse: Deep and shallow copies
© 2024 OneMinuteCode. All rights reserved.