Skip to content

Performance/ArraySemiInfiniteRangeSlice breaks code on Strings #197

@brushbox

Description

@brushbox

When running rubocop-performance over our code we noticed some autocorrections broke code.
The ArraySemiInfiniteRangeSlice rule was being applied to Strings but there is no String#drop method, leading to broken code.

See the minimal .rubocop.yml and sample.rb below for details.

Note: this also applies to non-obvious strings (returned from a method) and not just string literals.

The only workaround was to disable the rule.


Expected behavior

$ rubocop -a sample.rb 
Inspecting 1 file
.

1 file inspected, no offenses detected

And running sample.rb produces:

$ ruby sample.rb
ous string

Actual behavior

$ rubocop -a sample.rb
Inspecting 1 file
C

Offenses:

sample.rb:3:6: C: [Corrected] Performance/ArraySemiInfiniteRangeSlice: Use drop instead of [] with semi-infinite range.
puts 'an obvious string'[7..]
     ^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected

And running sample.rb produces:

$ ruby sample.rb
Traceback (most recent call last):
sample.rb:3:in `<main>': undefined method `drop' for "an obvious string":String (NoMethodError)

Steps to reproduce the problem

  1. Given the .rubocop.yml file:

    require:
      - rubocop-performance
    
    AllCops:
      NewCops: enable
      TargetRubyVersion: 2.7
  2. And the sample.rb file:

    # frozen_string_literal: true
    
    puts 'an obvious string'[7...]
  3. Run rubocop -a

  • the "violations" will be auto-corrected.
  1. Run ruby sample.rb
  • the code will break as there is no String#drop method.

RuboCop version

$ rubocop -V
1.3.1 (using Parser 2.7.2.0, rubocop-ast 1.1.1, running on ruby 2.7.1 x86_64-darwin19)
  - rubocop-performance 1.9.0

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