我误解了Array的行为
当我创建这个矩阵
matrix, cell = [], []; 5.times { cell << [] } # columns
3.times { matrix << cell } # lines
matrix
sample_data = (0..5).to_a
matrix[1][2] = sample_data.clone
matrix.each { |line| puts "line : #{line}" }
Run Code Online (Sandbox Code Playgroud)
我有这个结果
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
Run Code Online (Sandbox Code Playgroud)
而是预期的结果
line : [[], [], [], [], []]
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
line : [[], [], [], [], []]
Run Code Online (Sandbox Code Playgroud)
怎么了?
你的问题在于:
3.times { matrix << cell }
Run Code Online (Sandbox Code Playgroud)
您正在使用与cell三行相同的对象matrix.
关键是这Array是一个可变对象.即使您修改它,它的身份也不会改变.三次出现的情况cell都指向同一个实例(对象).如果您通过一次出现来访问和修改它,则其他出现将反映该变化.
如果您将此行更改为:
3.times { matrix << cell.dup }
Run Code Online (Sandbox Code Playgroud)
那么你将得到理想的结果.
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |