Method: String#change!

Defined in:
lib/mini_sanity/change.rb

#change!(pattern, replacement) ⇒ String #change!(pattern, hash) ⇒ String #change!(pattern) {|match| ... } ⇒ String

Like String#sub!, but raises an exception if no substitution is performed.

Examples:

info = "library: LIB_NAME\nlanguage: LIB_LANG\n"
info.change!(/\bLIB_NAME\b/, "mini_sanity")  # == "library: mini_sanity\nlanguage: LIB_LANG\n"
info                                         # == "library: mini_sanity\nlanguage: LIB_LANG\n"
info.change!(/\bLIB_LANGUAGE\b/, "Ruby")     # raises exception

Overloads:

  • #change!(pattern, replacement) ⇒ String

    Parameters:

    • pattern (Regexp, String)

      Pattern to search for

    • replacement (String)

      Replacement String (see String#sub documentation for more information)

    Returns:

    Raises:

  • #change!(pattern, hash) ⇒ String

    Parameters:

    • pattern (Regexp, String)

      Pattern to search for

    • hash (Hash)

      Substitution Hash (see String#sub documentation for more information)

    Returns:

    Raises:

  • #change!(pattern) {|match| ... } ⇒ String

    Parameters:

    Yield Parameters:

    • match (String)

      Matched String

    Yield Returns:

    • (String)

      Replacement String

    Returns:

    Raises:



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mini_sanity/change.rb', line 46

def change!(pattern, replacement = nil, &block)
  result = if replacement
    self.sub!(pattern, replacement)
  else
    self.sub!(pattern, &block)
  end

  if !result
    raise MiniSanity::Error.new("String does not match pattern", {
      "String" => self.inspect,
      "Pattern" => pattern.inspect,
    })
  end

  result
end