Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
String#scan
(::Regexp pattern) -> ::Array[::String | ::Array[::String?]]
(::Regexp pattern) { (::String | ::Array[::String?] matches) -> void } -> self
(::string pattern) -> ::Array[::String]
(::string pattern) { (::String match) -> void } -> self
scan(string_or_regexp) → array
scan(string_or_regexp) {|matches| ... } → self
string.c
View on GitHub ↗
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;
}
Matches a pattern against self; the pattern is:
-
string_or_regexpitself, if it is aRegexp. -
Regexp.quote(string_or_regexp), ifstring_or_regexpis 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:
Example
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:
Example
s.scan(/\w+/) {|w| print "<<#{w}>> " } print "\n" s.scan(/(.)(.)/) {|x,y| print y, x } print "\n"
Output:
<<cruel>> <<world>> rceu lowlr