0

i want to increment the loop iteration to next n rows if some condition matches.

sample code:

(8..spreadsheet.last_row).each do |i|
      spreadsheet_row = spreadsheet.row(i).compact
      next 3 if spreadsheet_row[0] == "Department:" # increment to next 3 row or skip the next 3 rows.
      next 6 if spreadsheet_row[0] == "Employee"  
end

but the next n is not working here, how to make this work.

2
  • You want to skip N elements? Commented Feb 3, 2015 at 7:41
  • am looping with excel sheet rows, after some rows in excel there are blank rows also there, so i want to skip those rows . Commented Feb 3, 2015 at 7:47

1 Answer 1

5

Good old manual index maintenance can help here

i = 8 # initial value
while i < spreadsheet.last_row # stop condition
  spreadsheet_row = spreadsheet.row(i).compact
  (i += 3; next) if spreadsheet_row[0] == "Department:" # jump over 3 rows
  (i += 6; next) if spreadsheet_row[0] == "Employee" # jump over 6 rows

  # some processing for current row is here

  i += 1 # advance to next row
end 

Alternatively, if you want, for example, to just skip blank rows (not fixed number), you can do simpler:

(8..spreadsheet.last_row).each do |i|
  spreadsheet_row = spreadsheet.row(i).compact
  next if blank_row?(spreadsheet_row) # implement blank_row?

  # regular processing here
end
Sign up to request clarification or add additional context in comments.

1 Comment

while loop increment is working fine, but is there any possible in for each loop to skip n elements . my above example not only blank row need to iterate every 6 row after some blank row to do some calculation.

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.