Rubocop:使用 next 跳过迭代

Rubocop: Use next to skip iteration

我从 Rubocop 那里得到 Style/Next: Use next to skip iteration. 的代码来做这样的事情(使用一个非常人为的例子):

tasks_running = [{ name: 'task1', done: false }, { name: 'task2', done: false }]
tasks_done = []

tasks_running.each do |task|
  if task[:done]
    unless tasks_done.include? task
      tasks_done << task
      next
    end
  end
end

I am 在嵌套条件下使用 next 跳过迭代。我不太明白如何满足这个标准。

我认为是在抱怨,因为如果 tasks_done 包含块中的当前任务,您可以使用 next,否则,将该任务推送到 tasks_done 数组:

tasks_running.each do |task|
  if task[:done]
    next if tasks_done.include?(task)
    tasks_done << task
  end
end

在你的例子中,下一条语句总是被评估,因为它是块中的最后一个表达式,它做了它必须做的所有事情,只是继续迭代,因为它不会在那里.

tasks_running.each do |task|
  if task[:done]                     # If true
    unless tasks_done.include?(task) # If true
      tasks_done << task             # Do this
      next                           # And jump to the next element
    end
  end
end