gpt4 book ai didi

arrays - 由于另一个数组,Ruby 空数组在迭代中更改值

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:50 25 4
gpt4 key购买 nike

一个空数组定义在 block 外,在 block 内,它被分配给一个新变量。如果新数组发生变化,空数组也会修改它的值。为什么?

# THIS CODE CHECK WHICH LETTERS IN klas APPEAR IN docs
klas = ["a", "b", "c"]

docs = [[1, "a"], [2, "a"], [3, "b"], [4, "b"], [5, "c"], [6, "c"]]

output = []
empty_array = Array.new(klas.size) { 0 } # EMPTY ARRAY DEFINED HERE

docs.each do |doc|
puts empty_array.inspect
puts (output_row = empty_array).inspect # EMPTY ARRAY ASSIGNED TO ANOTHER

# FIND INDEX OF THE LETTER IN klas FROM docs. ASSIGN 1.
output_row[klas.index(doc[1])] = 1 # PROBLEM! THIS ALSO CHANGES THE EMPTY ARRAY VALUES
output << output_row
end

CONSOLE OUTPUT 显示空数组根据另一个数组更改其值

###
empty_array is [0, 0, 0]
output_row is [0, 0, 0]
---
###
empty_array is [1, 0, 0]
output_row is [1, 0, 0]
---
###
empty_array is [1, 0, 0]
output_row is [1, 0, 0]
---
###
empty_array is [1, 1, 0]
output_row is [1, 1, 0]
---
###
empty_array is [1, 1, 0]
output_row is [1, 1, 0]
---
###
empty_array is [1, 1, 1]
output_row is [1, 1, 1]
---

# INCORRECT output IS
=> [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
# SHOULD BE
=> [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]

但如果空数组在 block 中定义并分配给一个新变量,它会按预期工作。

docs.each do |doc|
empty_array = Array.new(klas.size) { 0 } # THIS MAKES SURE empty_array stays with zero values
output_row = empty_array
output_row[klas.index(doc[1])] = 1
output << output_row
end

CORRECT output IS
=> [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]]

为什么空数组在 block 外时修改它的值?不管另一个数组改变它的值,它不应该保持不变吗?

最佳答案

通过使用

output_row = empty_array

您没有复制空数组。您正在创建对 empty_array 中引用的相同底层数组的引用。

您可以创建阵列的克隆或副本。所以使用:

output_row = empty_array.dup

这将创建一个新数组,它是 empty_array 的副本,参见 http://ruby-doc.org/core-2.4.1/Object.html#method-i-dup

关于示例发生的事情的更完整解释:

a = [1] => [1] # is creating a new array 'x'
# a is referencing this array, a is not the array itself!

b = a => [1] # b now references the array 'x'

a = [2] => [2] # is creating a new array 'y', a is referencing this new array
# the reference of b is not changing

b => [1] # b still pointing to array 'x'

所以对于 b = a 你只是告诉他们引用相同的数组 x,但是 b 不是对 的引用一个

关于arrays - 由于另一个数组,Ruby 空数组在迭代中更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45565014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com