Skip to content

RedundantStringChars is unsafe for autocorrection when string is too short or empty #471

@corsonknowles

Description

@corsonknowles

phone_number.number.chars[0..9]
autocorrected to:
phone_number.number[0..9].chars
This will raise when number[0..9] is blank.

Instead, it should be autocorrected to:
phone_number.number[0..9]&.chars

We have a similar nil handling problem when the string is too short instead of blank:

irb(main):001> twenty_character_string = "twenty_character_string"
=> "twenty_character_string"
irb(main):002> twenty_character_string[40..80].chars
(irb):2:in `<main>': undefined method `chars' for nil (NoMethodError)

twenty_character_string[40..80].chars
                               ^^^^^^

So the safe operator will make this safe.


Expected behavior

Expected autocorrect result to not raise error undefined method chars' for nil (NoMethodError)` for example by using a safe operator.

Actual behavior

Safe Autocorrect will create code that raises errors, either when the string is too short or when it's entirely empty (e.g. with a variable that can be blank or have a string of any length).

Steps to reproduce the problem

irb(main):001> twenty_character_string = "twenty_character_string"
=> "twenty_character_string"
irb(main):002> twenty_character_string[40..80].chars
(irb):2:in `<main>': undefined method `chars' for nil (NoMethodError)

twenty_character_string[40..80].chars
                               ^^^^^^

RuboCop version

Include the output of rubocop -V or bundle exec rubocop -V if using Bundler. Here's an example:
You can see extension cop versions (e.g. rubocop-performance, rubocop-rails, and others) output by rubocop -V,
include them as well. Here's an example:

rubocop -V
1.64.1 (using Parser 3.3.3.0, rubocop-ast 1.31.3, running on ruby 3.3.5) +server [arm64-darwin23]
  - rubocop-capybara 2.21.0
  - rubocop-factory_bot 2.26.1
  - rubocop-graphql 0.13.0
  - rubocop-gusto 5.3.5
  - rubocop-performance 1.21.1
  - rubocop-rails 2.25.0
  - rubocop-rake 0.6.0
  - rubocop-rspec 3.0.4
  - rubocop-sorbet 0.8.3

Background Docs:
https://msp-greg.github.io/rubocop-performance/RuboCop/Cop/Performance/RedundantStringChars.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions