使用其内容克隆数组

编程入门 行业动态 更新时间:2024-10-17 00:19:53
本文介绍了使用其内容克隆数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想要制作一个数组的副本,在原地修改副本,而不影响原始副本。此代码失败

a = ['462664','669722', '297288','796928','584497','357431'] b = a.clone b.object_id == a .object_id#=> false a [1] [2] ='X'a [1]#66X722 b [1]#66X722

副本应与对象不同。为什么它只是一个引用?

解决方案

p>

这是方法。

Marshal.load dump(a))

$ b $ p

这是因为你正在克隆数组,所以数组对象是不同的,但它包含的元素是相同的实例。你可以,例如,也可以做 a.each {| e | b<< e.dup} 为您的情况

I want to make a copy of an array, to modify the copy in-place, without affecting the original one. This code fails

a = [ '462664', '669722', '297288', '796928', '584497', '357431' ] b = a.clone b.object_id == a.object_id # => false a[1][2] = 'X' a[1] #66X722 b[1] #66X722

The copy should be different than the object. Why does it act like if it were just a reference?

解决方案

You need to do a deep copy of your array.

Here is the way to do it

Marshal.load(Marshal.dump(a))

This is because you are cloning the array but not the elements inside. So the array object is different but the elements it contains are the same instances. You could, for example, also do a.each{|e| b << e.dup} for your case

更多推荐

使用其内容克隆数组

本文发布于:2023-07-17 02:50:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   内容

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!