0
下面的代碼演示了一個ruby(1.8.7)for循環,其中從excel讀入的列和標題被保存爲對象(object attributes:header = string,contents =字符串數組)。當我在幾列閱讀時,我想將它們保存爲一組對象。向ruby循環中的數組添加對象將最新對象保留到所有數組項目
問題是每個循環在增加數組'矩陣'的同時,成功地存儲新對象,似乎用最新的對象覆蓋矩陣數組的前幾個元素。當我迭代完成的數組時,我只是得到同一個對象的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
請使用'.each'和'.each_with_index' – reto 2013-03-01 13:48:59