diff --git a/changelog/fix_an_incorrect_autocorrect_for_lint_symbol_conversion.md b/changelog/fix_an_incorrect_autocorrect_for_lint_symbol_conversion.md new file mode 100644 index 00000000000..4212fb1f36e --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_lint_symbol_conversion.md @@ -0,0 +1 @@ +* [#10462](https://github.com/rubocop/rubocop/issues/10462): Fix an incorrect autocorrect for `Lint/SymbolConversion` when using a quoted symbol key with hash rocket. ([@koic][]) diff --git a/lib/rubocop/cop/lint/symbol_conversion.rb b/lib/rubocop/cop/lint/symbol_conversion.rb index 826f3a39783..c748d2df002 100644 --- a/lib/rubocop/cop/lint/symbol_conversion.rb +++ b/lib/rubocop/cop/lint/symbol_conversion.rb @@ -147,13 +147,14 @@ def correct_hash_key(node) # will be ignored. return unless node.value.to_s.match?(/\A[a-z0-9_]/i) - correction = node.value.inspect.delete_prefix(':') + correction = node.value.inspect + correction = correction.delete_prefix(':') if node.parent.colon? return if properly_quoted?(node.source, correction) register_offense( node, correction: correction, - message: format(MSG, correction: "#{correction}:") + message: format(MSG, correction: node.parent.colon? ? "#{correction}:" : correction) ) end diff --git a/spec/rubocop/cop/lint/symbol_conversion_spec.rb b/spec/rubocop/cop/lint/symbol_conversion_spec.rb index 810d985c11a..fe536dc0353 100644 --- a/spec/rubocop/cop/lint/symbol_conversion_spec.rb +++ b/spec/rubocop/cop/lint/symbol_conversion_spec.rb @@ -121,7 +121,18 @@ RUBY end - it 'registers an offense for a quoted symbol' do + it 'registers an offense for a quoted symbol key' do + expect_offense(<<~RUBY) + { :'foo' => :bar } + ^^^^^^ Unnecessary symbol conversion; use `:foo` instead. + RUBY + + expect_correction(<<~RUBY) + { :foo => :bar } + RUBY + end + + it 'registers an offense for a quoted symbol value' do expect_offense(<<~RUBY) { foo: :'bar' } ^^^^^^ Unnecessary symbol conversion; use `:bar` instead.