Class: Regexp

Inherits:
Object show all
Defined in:
lib/eac_ruby_utils/patches/regexp/if_match.rb

Instance Method Summary collapse

Instance Method Details

#if_match(string, required = true, &block) ⇒ Object

If self matches string returns +block.call(Match result) or only Match result if block is not provided. If self does not match string raises a ArgumentError if required is truthy or return nil otherwise.



8
9
10
11
12
13
14
15
# File 'lib/eac_ruby_utils/patches/regexp/if_match.rb', line 8

def if_match(string, required = true, &block)
  m = match(string)
  if m
    block ? block.call(m) : m
  elsif required
    raise(::ArgumentError, "Pattern \"#{self}\" does not match string \"#{string}\"")
  end
end