Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an incorrect autocorrect for Performance/RedundantStringChars #273

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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