Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/pattern_patch/core_ext/string.rb

Instance Method Summary collapse

Instance Method Details

#apply_matches(matches) ⇒ String

Return a copy of the receiver with capture group references in self replaced by appropriate data from matches. The receiver need not match the matches.regexp.

Parameters:

  • matches (MatchData)

    A MatchData object returned by Regexp#match

Returns:

  • (String)

    A modified copy of the receiver



25
26
27
28
29
# File 'lib/pattern_patch/core_ext/string.rb', line 25

def apply_matches(matches)
  string = clone
  string.apply_matches! matches
  string
end

#apply_matches!(matches) ⇒ Object

Replace capture group references in self with appropriate data from matches. Modifies the receiver. The receiver need not match the matches.regexp.

Parameters:

  • matches (MatchData)

    A MatchData object returned by Regexp#match

Returns:

  • nil



8
9
10
11
12
13
14
15
16
17
# File 'lib/pattern_patch/core_ext/string.rb', line 8

def apply_matches!(matches)
  search_position = 0
  while (m = /\\(\d+)/.match(self, search_position))
    capture_group = m[1].to_i
    search_position = index m[0]
    gsub! m[0], matches[capture_group]
    search_position += matches[capture_group].length
  end
  nil
end