Skip to content

Commit

Permalink
Fix an incorrect autocorrect for Performance/RedundantStringChars
Browse files Browse the repository at this point in the history
Follow up to rubocop/rubocop-performance#249 (comment).

This PR fixes an incorrect autocorrect for `Performance/RedundantStringChars`
when using `str.chars[0]`.
  • Loading branch information
richardstewart0213 committed Nov 18, 2021
1 parent cd705a0 commit aeba999
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
@@ -0,0 +1 @@
* [#273](https://github.com/rubocop/rubocop-performance/pull/273): Fix an incorrect autocorrect for `Performance/RedundantStringChars` when using `str.chars[0]`. ([@koic][])
22 changes: 15 additions & 7 deletions lib/rubocop/cop/performance/redundant_string_chars.rb
Expand Up @@ -82,21 +82,29 @@ def build_message(method, args)

def build_good_method(method, args)
case method
when :[], :slice
when :slice
"[#{build_call_args(args)}].chars"
when :first
if args.any?
"[0...#{args.first.source}].chars"
else
'[0]'
end
when :[], :first
build_good_method_for_brackets_or_first_method(method, args)
when :take
"[0...#{args.first.source}].chars"
else
".#{method}"
end
end

def build_good_method_for_brackets_or_first_method(method, args)
first_arg = args.first

if first_arg&.range_type?
"[#{build_call_args(args)}].chars"
elsif method == :first && args.any?
"[0...#{args.first.source}].chars"
else
first_arg ? "[#{first_arg.source}]" : '[0]'
end
end

def build_bad_method(method, args)
case method
when :[]
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/performance/redundant_string_chars_spec.rb
Expand Up @@ -34,6 +34,28 @@
RUBY
end

it 'registers an offense and corrects when using `str.chars[0]`' do
expect_offense(<<~RUBY)
str.chars[0]
^^^^^^^^ Use `[0]` instead of `chars[0]`.
RUBY

expect_correction(<<~RUBY)
str[0]
RUBY
end

it 'registers an offense and corrects when using `str.chars[42]`' do
expect_offense(<<~RUBY)
str.chars[42]
^^^^^^^^^ Use `[42]` instead of `chars[42]`.
RUBY

expect_correction(<<~RUBY)
str[42]
RUBY
end

it 'registers an offense and corrects when using `str.chars.first(2)`' do
expect_offense(<<~RUBY)
str.chars.first(2)
Expand Down

0 comments on commit aeba999

Please sign in to comment.