【问题标题】:Rubocop: Use next to skip iterationRubocop:使用 next 跳过迭代
【发布时间】:2018-05-03 02:37:11
【问题描述】:

我从 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

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

【问题讨论】:

    标签: ruby rubocop


    【解决方案1】:

    我认为这是在抱怨,因为您可以使用 next 以防 tasks_done 包含块中的当前任务,否则,将该任务推送到 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
    

    【讨论】:

    • 是的,就是这样,使用next if。我现在明白,像这样跳出循环将产生与unless 相同的效果。
    猜你喜欢
    • 1970-01-01
    • 2011-08-06
    • 2015-06-20
    • 2011-06-28
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多