class RuboCop::Cop::Performance::EndWith
/bc$/.match(‘abc’)
‘abc’.match(/bc$/)
/bc$/ =~ ‘abc’
‘abc’ =~ /bc$/
/bc$/.match?(‘abc’)
‘abc’.match?(/bc$/)
# bad
@example SafeMultiline: false
/bc$/.match(‘abc’)
‘abc’.match(/bc$/)
/bc$/ =~ ‘abc’
‘abc’ =~ /bc$/
/bc$/.match?(‘abc’)
‘abc’.match?(/bc$/)
# good
@example SafeMultiline: true (default)
‘abc’.end_with?(‘bc’)
# good
/bcZ/.match(‘abc’)
‘abc’.match(/bcZ/)
/bcZ/ =~ ‘abc’
‘abc’ =~ /bcZ/
/bcZ/.match?(‘abc’)
‘abc’.match?(/bcZ/)
# bad
@example
for receiver is multiline string.
‘end$` is unsafe as it will behave incompatible with `end_with?`
This cop has `SafeMultiline` configuration option that `true` by default because
This cop identifies unnecessary use of a regex where `String#end_with?` would suffice.
def autocorrect(node)
def autocorrect(node) redundant_regex?(node) do |receiver, regex_str| receiver, regex_str = regex_str, receiver if receiver.is_a?(String) regex_str = drop_end_metacharacter(regex_str) regex_str = interpret_string_escapes(regex_str) lambda do |corrector| new_source = receiver.source + '.end_with?(' + to_string_literal(regex_str) + ')' corrector.replace(node.source_range, new_source) end end end
def on_send(node)
def on_send(node) return unless redundant_regex?(node) add_offense(node) end