以下代码演示了一个 ruby (1.8.7) for 循环,其中从 excel 读取的列和标题保存为对象(对象属性:标题=字符串,内容=字符串数组)。当我阅读几列时,我想将它们保存为对象数组。
问题是每个循环在增加数组“矩阵”并成功存储新对象的同时,似乎用最新的对象覆盖了矩阵数组的先前元素。当我遍历完成的数组时,我只得到同一个对象的 x 个实例。
column_count = count_columns(worksheet)
row_count = count_rows(worksheet)
matrix = Array.new
#i don't think header needs to be an array in the below loop, but anyway...
header = Array.new
contents = Array.new
for column in 0..column_count - 1
header[column] = worksheet.Cells(1, column + 2).Value
for row in 0..row_count
contents[row] = worksheet.Cells(row + 2, column + 2).Value
end
matrix[column] = Worksheet_Column.new(header[column], contents)
end
#looping after the array was created puts the same information in each iteration
for column in 0..matrix.length - 1
puts "loop = #{column}"
puts matrix[column]
end