Class: Uniword::FindReplace::StringMatcher

Inherits:
Matcher
  • Object
show all
Defined in:
lib/uniword/find_replace/string_matcher.rb

Overview

Literal substring matcher. Replaces every non-overlapping occurrence of pattern with replacement.

Instance Method Summary collapse

Constructor Details

#initialize(pattern:, replacement:, ignore_case: false) ⇒ StringMatcher

Returns a new instance of StringMatcher.

Parameters:

  • pattern (String)

    literal substring to find

  • replacement (String)

    replacement text

  • ignore_case (Boolean) (defaults to: false)

    match case-insensitively

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
# File 'lib/uniword/find_replace/string_matcher.rb', line 11

def initialize(pattern:, replacement:, ignore_case: false)
  raise ArgumentError, "pattern cannot be empty" if pattern.empty?

  @pattern = pattern
  @replacement = replacement
  @ignore_case = ignore_case
end

Instance Method Details

#apply(text) ⇒ Array(String, Integer)

Parameters:

  • text (String)

Returns:

  • (Array(String, Integer))


21
22
23
24
25
26
27
28
29
30
31
# File 'lib/uniword/find_replace/string_matcher.rb', line 21

def apply(text)
  unless text.include?(@pattern) || matches_ignore_case?(text)
    return [text,
            0]
  end

  text.size
  result = replace_all(text)
  substitutions = count_substitutions(text, result)
  [result, substitutions]
end