如何在接下来的n次迭代中为每个循环增加ruby

时间:2015-02-03 07:39:11

标签: ruby ruby-on-rails-4

如果某些条件匹配,我想将循环迭代增加到 next n 行。

示例代码:

(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

但下一个n在这里不起作用,如何使这项工作。

1 个答案:

答案 0 :(得分:2)

良好的旧手动索引维护可以在这里提供帮助

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 

或者,如果您想要跳过空白行(不是固定数字),您可以做得更简单:

(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