Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rubocop: Use next to skip iteration

Tags:

ruby

rubocop

I am getting Style/Next: Use next to skip iteration. from Rubocop for code that does something like this (using a very contrived example):

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 using next to skip iteration just within a nested condition. I don't quite understand how to satisfy this criteria.

like image 574
Friedrich 'Fred' Clausen Avatar asked Jan 28 '23 04:01

Friedrich 'Fred' Clausen


1 Answers

I think is complaining because you could use next in case tasks_done includes the current task from the block, and otherwise, push that task to the tasks_done array:

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

In your case, the next statement is being evaluate always, since is the last expression within the block, it does all what it must do, and just the continues with the iteration, is as it wouldn't be there.

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
like image 150
Sebastian Palma Avatar answered Feb 07 '23 14:02

Sebastian Palma