Class: RuboCop::Cop::Performance::RedundantStringChars

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/performance/redundant_string_chars.rb

Overview

Checks for redundant ‘String#chars`.

Examples:

# bad
str.chars[0..2]
str.chars.slice(0..2)
str.chars.last

# good
str[0..2].chars

# bad
str.chars.first
str.chars.first(2)

# good
str[0]
str[0...2].chars
str[-1]

# bad
str.chars.take(2)
str.chars.length
str.chars.size
str.chars.empty?

# good
str[0...2].chars
str.length
str.size
str.empty?

# For example, if the receiver is an empty string, it will be incompatible.
# If a negative value is specified for the receiver, `nil` is returned.
str.chars.last(2) # Incompatible with `str[-2..-1].chars`.
str.chars.drop(2) # Incompatible with `str[2..-1].chars`.

Constant Summary collapse

MSG =
'Use `%<good_method>s` instead of `%<bad_method>s`.'
RESTRICT_ON_SEND =
%i[[] slice first last take length size empty?].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/performance/redundant_string_chars.rb', line 54

def on_send(node)
  return unless (receiver, method, args = redundant_chars_call?(node))
  return if method == :last && !args.empty?

  range = offense_range(receiver, node)
  message = build_message(method, args)

  add_offense(range, message: message) do |corrector|
    range = correction_range(receiver, node)
    replacement = build_good_method(method, args)

    corrector.replace(range, replacement)
  end
end