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

Add new Style/StringChars cop #9615

Merged
merged 1 commit into from Mar 18, 2021

Commits on Mar 18, 2021

  1. Add new Style/StringChars cop

    ## Summary
    
    This PR adds new `Style/StringChars` cop. The cop checks for uses of
    `String#split` with empty string or regexp literal argument.
    
    ```ruby
    # bad
    string.split(//)
    string.split('')
    
    # good
    string.chars
    ```
    
    Since Ruby 2.0, the behavior of `String#chars` and `String#split(//)` is the same.
    
    ### Ruby 1.9 and lower
    
    ```console
    % ruby -ve "p 'foo'.split(//)"
    ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-darwin13.0.2]
    ["f", "o", "o"]
    % ruby -ve "p 'foo'.chars"
    ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-darwin13.0.2]
    #<Enumerator: "foo":chars>
    ```
    
    ### Ruby 2.0 and higher
    
    ```console
    % ruby -ve "p 'foo'.split(//)"
    ruby 2.0.0p648 (2015-12-16 revision 53162) [x86_64-darwin13.0.2]
    ["f", "o", "o"]
    % ruby -ve "p 'foo'.chars"
    ruby 2.0.0p648 (2015-12-16 revision 53162) [x86_64-darwin13.0.2]
    ["f", "o", "o"]
    ```
    
    Writing `String#chars` would pretty express the intent of the code.
    
    ## Additional Information
    
    This cop is intended to use `String#chars` method that express readable code.
    And it has a different purpose than `Performance/RedundantSplitRegexpArgument` cop.
    https://docs.rubocop.org/rubocop-performance/cops_performance.html#performanceredundantsplitregexpargument
    
    Therefore, it will be added as a new `Style` cop.
    koic committed Mar 18, 2021
    Copy the full SHA
    5fbfe36 View commit details
    Browse the repository at this point in the history