2

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.

2
  • is this a CSV file? if so, you can use ruby CSV Commented Aug 13, 2014 at 15:17
  • Does the array structure always be like this? Does always the datatype be always the same, means that starting from the second row you will have the first element as date and the rest as integers. Commented Aug 13, 2014 at 15:34

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

This only allows for fixed length rows.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.