Rubocop提示Style/Next:使用next跳过迭代的合规问题咨询
I get why this is confusing—you did use next, but Rubocop's Style/Next rule is more about flattening your logic by skipping unwanted iterations early rather than just dropping the keyword somewhere in nested conditions. Let's break this down and fix your code.
Your Original Code
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
What's the Problem?
Rubocop doesn't like that you're wrapping your core logic (adding the task to tasks_done) inside nested if/unless blocks. The rule's goal is to make your loop logic easier to scan: identify the cases you don't want to handle first, use next to skip those iterations immediately, and leave the code you do want to execute unindented at the top level of the block.
Fixed Code That Complies With Style/Next
tasks_running = [{ name: 'task1', done: false }, { name: 'task2', done: false }] tasks_done = [] tasks_running.each do |task| # Skip tasks that aren't completed yet next unless task[:done] # Skip tasks already in the done list next if tasks_done.include?(task) # Only run this code if both checks pass tasks_done << task end
Why This Works
- We use
nextto bail out of the iteration right away for invalid cases, instead of nesting the valid case under layers of conditions. - The code is flatter and more readable—anyone glancing at it can quickly see which tasks get skipped, and what happens to the ones that qualify.
- Rubocop will stop flagging this because we're using
nextexactly as the rule intends: to skip unwanted iterations early in the loop.
If you prefer a more concise version, you can combine the two next checks into one (though separate lines are generally more readable):
next unless task[:done] && !tasks_done.include?(task)
内容的提问来源于stack exchange,提问作者Friedrich 'Fred' Clausen

