diff --git a/changelog/fix_incorrect_autocorrect_for_style_hash_conversion.md b/changelog/fix_incorrect_autocorrect_for_style_hash_conversion.md new file mode 100644 index 00000000000..66032dbd04e --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_style_hash_conversion.md @@ -0,0 +1 @@ +* [#9672](https://github.com/rubocop/rubocop/issues/9672): Fix an incorrect auto-correct for `Style/HashConversion` when using multi-argument `Hash[]` as a method argument. ([@koic][]) diff --git a/lib/rubocop/cop/style/hash_conversion.rb b/lib/rubocop/cop/style/hash_conversion.rb index 90a65d60992..5566a1a9d7a 100644 --- a/lib/rubocop/cop/style/hash_conversion.rb +++ b/lib/rubocop/cop/style/hash_conversion.rb @@ -85,6 +85,9 @@ def multi_argument(node) else add_offense(node, message: MSG_LITERAL_MULTI_ARG) do |corrector| corrector.replace(node, args_to_hash(node.arguments)) + + parent = node.parent + add_parentheses(parent, corrector) if parent&.send_type? && !parent.parenthesized? end end end diff --git a/spec/rubocop/cop/style/hash_conversion_spec.rb b/spec/rubocop/cop/style/hash_conversion_spec.rb index 18558312698..4b188a26014 100644 --- a/spec/rubocop/cop/style/hash_conversion_spec.rb +++ b/spec/rubocop/cop/style/hash_conversion_spec.rb @@ -45,6 +45,17 @@ RUBY end + it 'registers and corrects an offense when using multi-argument `Hash[]` as a method argument' do + expect_offense(<<~RUBY) + do_something Hash[a, b, c, d], arg + ^^^^^^^^^^^^^^^^ Prefer literal hash to Hash[arg1, arg2, ...]. + RUBY + + expect_correction(<<~RUBY) + do_something({a => b, c => d}, arg) + RUBY + end + it 'does not try to correct multi-argument Hash with odd number of arguments' do expect_offense(<<~RUBY) Hash[a, b, c]