class RuboCop::Cop::Performance::DeleteSuffix
str.sub!(/suffix$/, ”)
str.sub(/suffix$/, ”)
str.gsub!(/suffix$/, ”)
str.gsub(/suffix$/, ”)
# bad
@example SafeMultiline: false
str.sub!(/suffix$/, ”)
str.sub(/suffix$/, ”)
str.gsub!(/suffix$/, ”)
str.gsub(/suffix$/, ”)
# good
@example SafeMultiline: true (default)
str.delete_suffix!(‘suffix’)
str.delete_suffix(‘suffix’)
# good
str.sub!(/suffixz/, ”)
str.sub(/suffixz/, ”)
str.gsub!(/suffixz/, ”)
str.gsub(/suffixz/, ”)
# bad
@example
This cop is unsafe because ‘Pathname` has `sub` but not `delete_suffix`.
@safety
The `delete_suffix(’suffix’)‘ method is faster than `gsub(/suffixz/, ”)`.
for receiver is multiline string.
`suffix$` is unsafe as it will behave incompatible with `delete_suffix?`
This cop has `SafeMultiline` configuration option that `true` by default because
can be replaced by `delete_suffix(’suffix’)‘.
This cop identifies places where `gsub(/suffixz/, ”)` and `sub(/suffixz/, ”)`
In Ruby 2.5, `String#delete_suffix` has been added.
def on_send(node)
def on_send(node) return unless (receiver, bad_method, regexp_str, replace_string = delete_suffix_candidate?(node)) return unless replace_string.empty? good_method = PREFERRED_METHODS[bad_method] message = format(MSG, current: bad_method, prefer: good_method) add_offense(node.loc.selector, message: message) do |corrector| regexp_str = drop_end_metacharacter(regexp_str) regexp_str = interpret_string_escapes(regexp_str) string_literal = to_string_literal(regexp_str) new_code = "#{receiver.source}#{node.loc.dot.source}#{good_method}(#{string_literal})" corrector.replace(node, new_code) end end