如何复制嵌套数组并确保副本是原始数组的完整副本
有没有一种简单的方法来复制嵌套数组,以便数组中的每个对象都将是原始对象的“重复”?我最近遇到了这个问题:
irb(main):001:0> a = [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
irb(main):002:0> b = a.dup
=> [[1, 2], [3, 4]]
irb(main):003:0> a[0][1] = 99
=> 99
irb(main):004:0> a
=> [[1, 99], [3, 4]]
irb(main):005:0> b
=> [[1, 99], [3, 4]]
irb(main):006:0> a[0] = [101,102]
=> [101, 102]
irb(main):007:0> a
=> [[101, 102], [3, 4]]
irb(main):008:0> b
=> [[1, 99], [3, 4]]
因此,虽然 a
中的第一级数组是单独的对象,但它们的内容不是,a[0][1]
仍然等于 <代码>b[0][1]。通用解决方案甚至不必知道数组嵌套的深度。对我来说,遍历每个对象并使其成为其自身的副本听起来有点蛮力。
Is there an easy way to copy a nested Array so that every object in the array will be a 'dup' of the original? I recently run into this:
irb(main):001:0> a = [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
irb(main):002:0> b = a.dup
=> [[1, 2], [3, 4]]
irb(main):003:0> a[0][1] = 99
=> 99
irb(main):004:0> a
=> [[1, 99], [3, 4]]
irb(main):005:0> b
=> [[1, 99], [3, 4]]
irb(main):006:0> a[0] = [101,102]
=> [101, 102]
irb(main):007:0> a
=> [[101, 102], [3, 4]]
irb(main):008:0> b
=> [[1, 99], [3, 4]]
So while the first level of arrays in a
were individual objects, their content were not, a[0][1]
is still equal to b[0][1]
. A general solution don't even have to know how deeply an array is nested. Walking through every object and make it a dup of itself sounds a bit brute-force to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)