Mani David
Mani David

Reputation: 1412

How to increment ruby for each loop with next n iterations

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.

Upvotes: 0

Views: 4673

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

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

Upvotes: 5

Related Questions