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

False positive for IfUnlessModifier with pattern matching #11723

Closed
mehanoid opened this issue Mar 20, 2023 · 0 comments · Fixed by #11724
Closed

False positive for IfUnlessModifier with pattern matching #11723

mehanoid opened this issue Mar 20, 2023 · 0 comments · Fixed by #11724
Labels

Comments

@mehanoid
Copy link

If an if condition contains a pattern matching with a variable assignment, rubocop may erroneously suggest changing this code to use an if modifier, but the changed code does not work.


Expected behavior

No offences, no autocorrection

Actual behavior

For /home/meh/Projects/sandbox: Default configuration from /home/meh/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/rubocop-1.48.1/config/default.yml
Use parallel by default.
Skipping parallel inspection: only a single file needs inspection
Inspecting 1 file
Scanning /home/meh/Projects/sandbox/rubocop_pattern_match.rb
C

Offenses:

rubocop_pattern_match.rb:3:1: C: [Correctable] Style/IfUnlessModifier: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.
if [1] in [x]
^^

1 file inspected, 1 offense detected, 1 offense autocorrectable
Finished in 0.1424515729995619 seconds

Code after autocorrection:

# frozen_string_literal: true

puts x if [1] in [x]

This code does not work because the variables declared to the right of if are not visible to the code to the left of if. As a result, we get an error:

undefined local variable or method `x' for main:Object (NameError)

puts x if [1] in [x]
     ^

Steps to reproduce the problem

# frozen_string_literal: true

if [1] in [x]
  puts x
end

RuboCop version

$ rubocop -V
1.48.1 (using Parser 3.2.1.0, rubocop-ast 1.27.0, running on ruby 3.2.1) [x86_64-linux]
@koic koic added the bug label Mar 21, 2023
koic added a commit to koic/rubocop that referenced this issue Mar 22, 2023
Fixes rubocop#11723.

This PR fixes a false positive for `Style/IfUnlessModifier`
when using one-line pattern matching as a `if` condition.
bbatsov pushed a commit that referenced this issue Mar 23, 2023
Fixes #11723.

This PR fixes a false positive for `Style/IfUnlessModifier`
when using one-line pattern matching as a `if` condition.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants