2013-03-01 59 views
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 
+0

请使用'.each'和'.each_with_index' – reto 2013-03-01 13:48:59

回答

0

嗯,我还没有看到基本的错误允许哪些内容向后写,但已经注意到发生了内容的问题,而不是页眉这一解决方案已经成功。

for column in 0..column_count - 1 
    contents[column] = Array.new 
    header[column] = worksheet.Cells(1, column + 2).Value 
    for row in 0..row_count 
    contents[column][row] = worksheet.Cells(row + 2, column + 2).Value 
    end 
    matrix[column] = Worksheet_Column.new(header[column], contents[column]) 
end