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

Style/CombinableLoops autocorrects loops with different element names #13202

Closed
Zopolis4 opened this issue Sep 6, 2024 · 0 comments · Fixed by #13203
Closed

Style/CombinableLoops autocorrects loops with different element names #13202

Zopolis4 opened this issue Sep 6, 2024 · 0 comments · Fixed by #13203
Labels

Comments

@Zopolis4
Copy link
Contributor

Zopolis4 commented Sep 6, 2024

Given the following example code:

# frozen_string_literal: true

array = %w[foo bar baz]

array.each do |i|
  puts i
end

array.each do |q|
  puts q
end

with the following output:

$ ruby test.rb
foo
bar
baz
foo
bar
baz

rubocop autocorrects it to:

# frozen_string_literal: true

array = %w[foo bar baz]

array.each do |i|
  puts i

  puts q
end

which breaks when run:

$ ruby test.rb
foo
test.rb:8:in `block in <main>': undefined local variable or method `q' for main:Object (NameError)

  puts q
       ^
        from test.rb:5:in `each'
        from test.rb:5:in `<main>'

Expected behavior

To not generate invalid code, so either:

  • recognizing that the two loops use different names for their element and not combining them
  • changing instances of the element name in the second loop to match the identifier given in the first loop.

Actual behavior

Rubocop combined the two loops even though they used different element names, leading to the second one now having an unidentified variable.

I know that Style/CombinableLoops is marked as unsafe, but I presume generating invalid code is still a bug? If it is not, my apologies for the invalid report.

Steps to reproduce the problem

Run rubocop on the provided example code and autocorrect the Style/CombinableLoops offenses, then run the resulting code.

RuboCop version

$ rubocop -V
1.66.1 (using Parser 3.3.5.0, rubocop-ast 1.32.3, running on ruby 3.1.2) [x86_64-linux-gnu]
@koic koic added the bug label Sep 6, 2024
koic added a commit to koic/rubocop that referenced this issue Sep 6, 2024
…eLoops`

Fixes rubocop#13202.

This PR fixes an incorrect autocorrect for `Style/CombinableLoops`
when looping over the same data with different block variable names.
koic added a commit to koic/rubocop that referenced this issue Sep 27, 2024
…eLoops`

Fixes rubocop#13202.

This PR fixes an incorrect autocorrect for `Style/CombinableLoops`
when looping over the same data with different block variable names.
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