bopritchard
bopritchard

Reputation: 399

Update array while iterating in ruby

I have an array where the first row contain headers and the first column contains dates. And the last column in the array is for Totals.

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

I need to sum up the values of columns per row and update the last column with that value. Here's what I've done thus far. It's the part where I actually change the value of the array I can't quit get.

  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: My apologies if I haven't formatted this correctly. I'm trying to learn how to make my questions look nice.

Upvotes: 2

Views: 1466

Answers (2)

Matt
Matt

Reputation: 14038

You need to use the length of the row to check if you are on the last column, not the value in the column. You also then need to set the value on the row (by index) rather than changing the value of the local col object.

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 

And see MrYoshiji's answer for removing the first row from your data if you need to. My answer will not do so, meaning the final array still includes the headers.

Upvotes: 0

MrYoshiji
MrYoshiji

Reputation: 54882

You can use .shift to remove the first element of the array (which is an array containg the column's names):

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

Then you can loop on the data arrays and sum the desired columns:

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

Upvotes: 2

Related Questions