在ruby中迭代时更新数组

时间:2014-08-13 15:10:54

标签: ruby-on-rails arrays

我有一个数组,其中第一行包含标题,第一列包含日期。数组中的最后一列是Totals。

[["date",  "Fish",  "Bear",  "Cat",  "Total"],  
["8/1/2014",  5,  3,  6,  0],   
["8/1/2014",  2,  6,  3,  0]] 

我需要总结每行的列值并使用该值更新最后一列。这是我到目前为止所做的。这是我实际更改我无法退出的数组值的部分。

  arr.each_with_index do |row,index|
    sum = 0
    next if index == 0
    row.each_with_index do |col,index2|
      next if index2 ==0
      if (col == row.last)
        #update the col with the value of sum
      end
      sum += col.to_i
    end
  end 

PS:如果我没有正确格式化,我很抱歉。我正在努力学习如何使我的问题看起来很好。

2 个答案:

答案 0 :(得分:2)

您可以使用.shift删除数组的第一个元素(这是一个包含列名称的数组):

data = [["date",  "Fish",  "Bear",  "Cat",  "Total"],  
["8/1/2014",  5,  3,  6,  0],   
["8/1/2014",  2,  6,  3,  0]]
headers = data.shift # now data contains only the values, not the header

然后你可以循环data数组并总结所需的列:

data.each_with_index do |row, i|
  total = row[1] + row[2] + row[3]
  row[4] = total
end

答案 1 :(得分:0)

您需要使用行的长度来检查您是否在最后一列,而不是列中的值。然后,您还需要在行上设置值(按索引),而不是更改本地col对象的值。

arr.each_with_index do |row,index|
  sum = 0
  next if index == 0
  row.each_with_index do |col,index2|
    next if index2 == 0
    if (index2 == row.length - 1)  
      row[index2] = sum
    else
      sum += col.to_i
    end
  end
end 

如果需要,请参阅MrYoshiji's answer以从数据中删除第一行。我的答案不会这样做,这意味着最终的数组仍然包含标题。