本文介绍了在 Ruby 中使用 .clear 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法在标题中足够简洁地解释我的问题,所以我把它放在这里.在问我的问题之前显示代码实际上会更容易:

Couldn't explain my question succinctly enough in the title, so I'm putting it here. It will actually be easier to show the code before asking my question:

array1 = []
array2 = [1,2,3]

array1 = array2
#=> array1 = [1,2,3]

array2.clear

#=> array1 = []
#=> array2 = []

为什么在第二个数组上使用 .clear 方法也会清除第一个数组中的内容?我想我要问的是,一旦我们设置了 array1 = array2,为什么 array1 会受到我们应用于 .clear 的影响>array2?似乎 array1 = array2 在我的脚本执行期间都成立,对吗?

Why does using the .clear method on the second array also clear what is in the first array? I guess what I'm asking is, once we set array1 = array2, why is array1 affected by the .clear we apply to array2? It seems that array1 = array2 will hold true for the duration of my script, is this right?

为了使 array1 在我执行 array2.clear 后保持不变,我是否需要以不同的方式实现 array1 = array2,例如使用 for 循环和 .unshift 元素从 array2.push>array1?

In order for array1 to remain unchanged once I do array2.clear, would I need to implement array1 = array2 a different way, such as using a for loop and .unshifting elements from array2 and .pushing them over to array1?

推荐答案

什么时候做

array1 = array2

array1array2 现在引用同一个 Array 对象.因此,您对其中任何一个所做的任何修改都会影响另一个.

array1 and array2 reference to the same Array object now. So any modifications you make to either will affect to the other.

array1.object_id
# => 2476740
array2.object_id
# => 2476740

看到了吗?它们具有相同的 object_id.

See? They have the same object_id.

如果此行为不是您所期望的,请尝试

If this behavior is not what you expected, try

array1 = array2.dup

array1 = array2.clone

这篇关于在 Ruby 中使用 .clear 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 07:06