become the same before and after the sequence is converted

Asked 2 years ago, Updated 2 years ago, 35 views

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?

ruby

2022-09-30 18:11

1 Answers

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


2022-09-30 18:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.