Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lint/ShadowingOuterLocalVariable does not take into account if/else branches #12872

Closed
postmodern opened this issue Apr 29, 2024 · 1 comment
Closed
Labels

Comments

@postmodern
Copy link

postmodern commented Apr 29, 2024

Lint/ShadowingOuterLocalVariable appears to be incorrectly flagging using of a local variable in one branch of an if/else statement, where the other branch re-uses the same variable name for a block variable. Since only one of the if/else branches can ever execute, this should not cause any problems.

Steps To Reproduce

Gemfile:

source 'https://rubygems.org'

gem 'rubocop'
def test(obj, first: false)
  if first
    if (thing = get_first_thing(obj))
      print_thing(thing)
      yield thing
    end
  else
    get_things(obj) do |thing|
      print_thing(thing)
      yield thing
    end
  end
end

Expected behavior

No warnings.

Actual behavior

test.rb:8:25: W: Lint/ShadowingOuterLocalVariable: Shadowing outer local variable - thing.
    get_things(obj) do |thing|
                        ^^^^^

RuboCop version

$ bundle exec rubocop -V
1.63.4 (using Parser 3.3.1.0, rubocop-ast 1.31.2, running on ruby 3.2.4) [x86_64-linux]
@postmodern postmodern changed the title Lint/ShadowingOuterLocalVariable does not take into account if/else branching Lint/ShadowingOuterLocalVariable does not take into account if/else branches Apr 29, 2024
@koic koic added the bug label Apr 29, 2024
@postmodern
Copy link
Author

It has come to my attention that Ruby will define local variables even in branches that are not executed.

def test
  if false
    x = 1
  else
  end
  local_variables
end

test
# => [:x]

So rubocop is technically correct here.

@postmodern postmodern closed this as not planned Won't fix, can't repro, duplicate, stale Apr 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants