Skip to content

Lint/UselessAssignment false positive #14559

@patbl

Description

@patbl

Expected behavior

Lint/UselessAssignment doesn't flag necessary assignments.

Actual behavior

def foo
  keep_going = true
  while keep_going
    keep_going = false # This assignment is flagged.
    if rand < 0.5
      keep_going = true
    end
  end
  puts "done"
end

foo

Steps to reproduce the problem

Create a file foo.rb containing this code:

def foo
  keep_going = true
  while keep_going
    keep_going = false
    if rand < 0.5
      keep_going = true
    end
  end
  puts "done"
end

foo

Run rubocop --only Lint/UselessAssignment --autocorrect foo.rb.

This is the output:

[...]
Inspecting 1 file
W

Offenses:

foo.rb:4:5: W: [Corrected] Lint/UselessAssignment: Useless assignment to variable - keep_going.
    keep_going = false
    ^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected

The program is changed to

def foo
  keep_going = true
  while keep_going
    false
    if rand < 0.5
      keep_going = true
    end
  end
  puts "done"
end

foo

That is, keep_going = false is turned into false.

Now, if you run ruby foo.rb, the program never finishes running.

RuboCop version

$ rubocop -V
1.80.2 (using Parser 3.3.9.0, Prism 1.5.1, rubocop-ast 1.47.1, analyzing as Ruby 3.4, running on ruby 3.4.1) [x86_64-darwin24]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions