Skip to content

Fix an incorrect autocorrect for Style/EmptyLiteral with Hash[] as the first argument - #15863

Merged
koic merged 1 commit into
rubocop:masterfrom
kevin9327:fix-empty-literal-hash-brackets
Oct 5, 2026
Merged

koic merged 1 commit into
rubocop:masterfrom
kevin9327:fix-empty-literal-hash-brackets

Conversation

@kevin9327

@kevin9327 kevin9327 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

When Hash[] or Hash([]) is the first argument of a method call without parentheses, Style/EmptyLiteral autocorrects it into invalid Ruby:

assert_equal Hash[], foo
# autocorrected to:
assert_equal ({}, foo), foo   # SyntaxError

Hash.new in the same position is corrected properly to assert_equal({}, foo).

The cause is that correction uses offense_hash_node?, which covers Hash.new, Hash[] and Hash([]), so it builds the parenthesized argument list ({}, foo). But replacement_range only checked hash_node, which matches Hash.new alone. For Hash[] and Hash([]) the replacement therefore went over just the receiver node instead of the whole argument list. replacement_range now uses offense_hash_node? as well.

I found this by running rubocop -A over a corpus of popular gems and checking the corrected files with ruby -c. It hit rack/test/spec_headers.rb (assert_equal Hash[], Rack::Headers[]).

I added specs for Hash[] with a following argument and for Hash([]) as the only argument. Both fail on master and pass with this change. All of spec/rubocop/cop/style passes (15,595 examples), and RuboCop reports no offenses on the changed files. I did not run the full rake default.


  • The PR relates to only one subject with a clear title and description in grammatically correct, complete sentences.
  • Wrote good commit messages.
  • Feature branch is up-to-date with master (if not - rebase it).
  • Squashed related commits together.
  • Added tests.
  • Ran bundle exec rake default. It executes all tests and runs RuboCop on its own code.
  • Added an entry (file) to the changelog folder named {change_type}_{change_description}.md if the new code introduces user-observable changes. See changelog entry format for details.

@koic
koic merged commit 336853e into rubocop:master Oct 5, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants