Skip to content

Commit

Permalink
Fix false positive for Style/EmptyLiteral with Hash.new([])
Browse files Browse the repository at this point in the history
The first parameter for Hash.new is the default value:

```rb
Hash.new([])[:foo]
# => []
```

Side note: this usage is most likely a programming error. You want the block form
where different keys _don't_ share the same underlying array.
  • Loading branch information
Earlopain committed Sep 1, 2024
1 parent 7bb9708 commit 60d3cd6
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_positive_empty_literal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#13178](https://github.com/rubocop/rubocop/pull/13178): Fix false positive for `Style/EmptyLiteral` with `Hash.new([])`. ([@earlopain][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/empty_literal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class EmptyLiteral < Base
def_node_matcher :array_node, '(send (const {nil? cbase} :Array) :new (array)?)'

# @!method hash_node(node)
def_node_matcher :hash_node, '(send (const {nil? cbase} :Hash) :new (array)?)'
def_node_matcher :hash_node, '(send (const {nil? cbase} :Hash) :new)'

# @!method str_node(node)
def_node_matcher :str_node, '(send (const {nil? cbase} :String) :new)'
Expand Down
5 changes: 4 additions & 1 deletion spec/rubocop/cop/style/empty_literal_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@
it_behaves_like 'registers_and_corrects', initializer: 'Hash.new()'
it_behaves_like 'registers_and_corrects', initializer: 'Hash.new'
it_behaves_like 'registers_and_corrects', initializer: '::Hash.new()'
it_behaves_like 'registers_and_corrects', initializer: 'Hash.new([])'
it_behaves_like 'registers_and_corrects', initializer: 'Hash[]'
it_behaves_like 'registers_and_corrects', initializer: 'Hash([])'
end
Expand Down Expand Up @@ -107,6 +106,10 @@
expect_no_offenses('test = ::Hash.new { block }')
end

it 'does not register an offense for Hash.new([])' do
expect_no_offenses('Hash.new([])')
end

context 'Ruby 2.7', :ruby27 do
it 'does not register an offense for Hash.new { _1[_2] = [] }' do
expect_no_offenses('test = Hash.new { _1[_2] = [] }')
Expand Down

0 comments on commit 60d3cd6

Please sign in to comment.