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/HashAsLastArrayItem copy with style "no_braces" can result in invalid code #8475

Closed
wcmonty opened this issue Aug 6, 2020 · 0 comments · Fixed by #8477
Closed

Style/HashAsLastArrayItem copy with style "no_braces" can result in invalid code #8475

wcmonty opened this issue Aug 6, 2020 · 0 comments · Fixed by #8477
Labels

Comments

@wcmonty
Copy link

wcmonty commented Aug 6, 2020

Expected behavior

Using Style/HashAsLastArrayItem with EnforcedStyle: no_braces should yield valid Ruby code when there are duplicate Hashes in the array. This is similar to #8323, but has not been fully resolved when there are identical hashes in the array.

Actual behavior

The cop is not safe and results in invalid Ruby code.

Steps to reproduce the problem

# .rubocop.yml
AllCops:
  NewCops: enable

Style/HashAsLastArrayItem:
  EnforcedStyle: no_braces
# hash_as_last_array_item.rb before
# frozen-string-literal: true

# Note that the hashes are identical
a = [
  {
    foo: :bar,
  },
  {
    foo: :bar
  }
]

pp a
$ ruby hash_as_last_array_item.rb
[{:foo=>:bar}, {:foo=>:bar}]
$ rubocop -a hash_as_last_array_item.rb
Inspecting 1 file
E

Offenses:

hash_as_last_array_item.rb:5:3: C: [Corrected] Style/HashAsLastArrayItem: Omit the braces around the hash.
  { ...
  ^
hash_as_last_array_item.rb:6:14: C: [Corrected] Style/TrailingCommaInHashLiteral: Avoid comma after the last item of a hash.
    foo: :bar,
             ^
hash_as_last_array_item.rb:7:3: E: Lint/Syntax: unexpected token tCOMMA
(Using Ruby 2.4 parser; configure using TargetRubyVersion parameter, under AllCops)
  ,
  ^
hash_as_last_array_item.rb:8:3: C: [Corrected] Style/HashAsLastArrayItem: Omit the braces around the hash.
  { ...
  ^

1 file inspected, 4 offenses detected, 3 offenses corrected
# hash_as_last_array_item.rb after
# frozen-string-literal: true

a = [

    foo: :bar
  ,

    foo: :bar

]

pp a
$ ruby hash_as_last_array_item.rb
hash_as_last_array_item.rb:7: syntax error, unexpected ',', expecting ']'
hash_as_last_array_item.rb:11: syntax error, unexpected ']', expecting end-of-input

RuboCop version

$ rubocop -v
0.89.0
@koic koic added the bug label Aug 6, 2020
@koic koic closed this as completed in #8477 Aug 8, 2020
koic added a commit that referenced this issue Aug 8, 2020
[Fix #8475] Fix a false positive for Style/HashAsLastArrayItem when t…
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