Method: String#scan
- Defined in:
- string.c
#scan(string_or_regexp) ⇒ Array #scan(string_or_regexp) {|matches| ... } ⇒ self
Matches a pattern against self
; the pattern is:
-
string_or_regexp
itself, if it is a Regexp. -
Regexp.quote(string_or_regexp)
, ifstring_or_regexp
is a string.
Iterates through self
, generating a collection of matching results:
-
If the pattern contains no groups, each result is the matched string,
$&
. -
If the pattern contains groups, each result is an array containing one entry per group.
With no block given, returns an array of the results:
s = 'cruel world'
s.scan(/\w+/) # => ["cruel", "world"]
s.scan(/.../) # => ["cru", "el ", "wor"]
s.scan(/(...)/) # => [["cru"], ["el "], ["wor"]]
s.scan(/(..)(..)/) # => [["cr", "ue"], ["l ", "wo"]]
With a block given, calls the block with each result; returns self
:
s.scan(/\w+/) {|w| print "<<#{w}>> " }
print "\n"
s.scan(/(.)(.)/) {|x,y| print y, x }
print "\n"
Output:
<<cruel>> <<world>>
rceu lowlr
10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 |
# File 'string.c', line 10556
static VALUE
rb_str_scan(VALUE str, VALUE pat)
{
VALUE result;
long start = 0;
long last = -1, prev = 0;
char *p = RSTRING_PTR(str); long len = RSTRING_LEN(str);
pat = get_pat_quoted(pat, 1);
mustnot_broken(str);
if (!rb_block_given_p()) {
VALUE ary = rb_ary_new();
while (!NIL_P(result = scan_once(str, pat, &start, 0))) {
last = prev;
prev = start;
rb_ary_push(ary, result);
}
if (last >= 0) rb_pat_search(pat, str, last, 1);
else rb_backref_set(Qnil);
return ary;
}
while (!NIL_P(result = scan_once(str, pat, &start, 1))) {
last = prev;
prev = start;
rb_yield(result);
str_mod_check(str, p, len);
}
if (last >= 0) rb_pat_search(pat, str, last, 1);
return str;
}
|