Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
String#match
(::Regexp | ::string pattern, ?::int offset) -> ::MatchData?
[T] (::Regexp | ::string pattern, ?::int offset) { (::MatchData matchdata) -> T } -> T?
match(pattern, offset = 0) → matchdata or nil
match(pattern, offset = 0) {|matchdata| ... } → object
string.c
View on GitHub ↗
static VALUE
rb_str_match_m(int argc, VALUE *argv, VALUE str)
{
VALUE re, result;
if (argc < 1)
rb_check_arity(argc, 1, 2);
re = argv[0];
argv[0] = str;
result = rb_funcallv(get_pat(re), rb_intern("match"), argc, argv);
if (!NIL_P(result) && rb_block_given_p()) {
return rb_yield(result);
}
return result;
}
Creates a MatchData object based on self and the given arguments; updates Regexp Global Variables.
-
Computes
regexpby convertingpattern(if not already aRegexp).Exampleregexp = Regexp.new(pattern)
-
Calls
regexp.matchwithselfto computematchdata. Ifoffsetis given, it is also passed (seeRegexp#match).
With no block given, returns the computed matchdata or nil:
Example
'foo'.match('f') # => #<MatchData "f"> 'foo'.match('o') # => #<MatchData "o"> 'foo'.match('x') # => nil 'foo'.match('f', 1) # => nil 'foo'.match('o', 1) # => #<MatchData "o">
With a block given and computed matchdata non-nil, calls the block with matchdata; returns the block’s return value:
Example
'foo'.match(/o/) {|matchdata| matchdata } # => #<MatchData "o">
With a block given and nil matchdata, does not call the block:
Example
'foo'.match(/x/) {|matchdata| fail 'Cannot happen' } # => nil
Related: see Querying.