class RuboCop::Cop::Performance::RedundantSplitRegexpArgument

This cop identifies places where `split` argument can be replaced from a deterministic regexp to a string.

@example

# bad
'a,b,c'.split(/,/)

# good
'a,b,c'.split(',')

Constants

DETERMINISTIC_REGEX
MSG
RESTRICT_ON_SEND
STR_SPECIAL_CHARS

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/performance/redundant_split_regexp_argument.rb, line 27
def on_send(node)
  return unless (regexp_node = split_call_with_regexp?(node))
  return if regexp_node.ignore_case? || regexp_node.content == ' '
  return unless determinist_regexp?(regexp_node)

  add_offense(regexp_node) do |corrector|
    new_argument = replacement(regexp_node)

    corrector.replace(regexp_node, "\"#{new_argument}\"")
  end
end

Private Instance Methods

determinist_regexp?(regexp_node) click to toggle source
# File lib/rubocop/cop/performance/redundant_split_regexp_argument.rb, line 41
def determinist_regexp?(regexp_node)
  DETERMINISTIC_REGEX.match?(regexp_node.source)
end
replacement(regexp_node) click to toggle source
# File lib/rubocop/cop/performance/redundant_split_regexp_argument.rb, line 45
def replacement(regexp_node)
  regexp_content = regexp_node.content
  stack = []
  chars = regexp_content.chars.each_with_object([]) do |char, strings|
    if stack.empty? && char == '\\'
      stack.push(char)
    else
      strings << "#{stack.pop}#{char}"
    end
  end
  chars.map do |char|
    char = char.dup
    char.delete!('\\') unless STR_SPECIAL_CHARS.include?(char)
    char
  end.join
end