Method: String#match
- Defined in:
- string.c
#match(pattern) ⇒ MatchData? #match(pattern, pos) ⇒ MatchData?
Converts pattern to a Regexp (if it isn’t already one), then invokes its match
method on str. If the second parameter is present, it specifies the position in the string to begin the search.
'hello'.match('(.)\1') #=> #<MatchData "ll" 1:"l">
'hello'.match('(.)\1')[0] #=> "ll"
'hello'.match(/(.)\1/)[0] #=> "ll"
'hello'.match(/(.)\1/, 3) #=> nil
'hello'.match('xx') #=> nil
If a block is given, invoke the block with MatchData if match succeed, so that you can write
str.match(pat) {|m| ...}
instead of
if m = str.match(pat)
...
end
The return value is a value from block execution in this case.
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 |
# File 'string.c', line 3838
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;
}
|