Class: RuboCop::Cop::Performance::StringReplacement

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

Overview

Identifies places where ‘gsub` can be replaced by `tr` or `delete`.

Examples:

# bad
'abc'.gsub('b', 'd')
'abc'.gsub('a', '')
'abc'.gsub(/a/, 'd')
'abc'.gsub!('a', 'd')

# good
'abc'.gsub(/.*/, 'a')
'abc'.gsub(/a+/, 'd')
'abc'.tr('b', 'd')
'a b c'.delete(' ')

Constant Summary collapse

MSG =
'Use `%<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND =
%i[gsub gsub!].freeze
DETERMINISTIC_REGEX =
/\A(?:#{LITERAL_REGEX})+\Z/.freeze
DELETE =
'delete'
TR =
'tr'
BANG =
'!'

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



37
38
39
40
41
42
43
44
# File 'lib/rubocop/cop/performance/string_replacement.rb', line 37

def on_send(node)
  string_replacement?(node) do |first_param, second_param|
    return if accept_second_param?(second_param)
    return if accept_first_param?(first_param)

    offense(node, first_param, second_param)
  end
end