class RuboCop::Cop::Performance::EndWith
This cop identifies unnecessary use of a regex where `String#end_with?` would suffice.
This cop has `SafeMultiline` configuration option that `true` by default because `end$` is unsafe as it will behave incompatible with `end_with?` for receiver is multiline string.
@example
# bad 'abc'.match?(/bc\Z/) /bc\Z/.match?('abc') 'abc' =~ /bc\Z/ /bc\Z/ =~ 'abc' 'abc'.match(/bc\Z/) /bc\Z/.match('abc') # good 'abc'.end_with?('bc')
@example SafeMultiline: true (default)
# good 'abc'.match?(/bc$/) /bc$/.match?('abc') 'abc' =~ /bc$/ /bc$/ =~ 'abc' 'abc'.match(/bc$/) /bc$/.match('abc')
@example SafeMultiline: false
# bad 'abc'.match?(/bc$/) /bc$/.match?('abc') 'abc' =~ /bc$/ /bc$/ =~ 'abc' 'abc'.match(/bc$/) /bc$/.match('abc')
Constants
- MSG
- RESTRICT_ON_SEND
Public Instance Methods
on_send(node)
click to toggle source
# File lib/rubocop/cop/performance/end_with.rb, line 58 def on_send(node) return unless (receiver, regex_str = redundant_regex?(node)) add_offense(node) do |corrector| 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) new_source = "#{receiver.source}.end_with?(#{to_string_literal(regex_str)})" corrector.replace(node.source_range, new_source) end end
Also aliased as: on_match_with_lvasgn