Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#scan

scan(string_or_regexp) → array
scan(string_or_regexp) {|matches| ... } → self

Matches a pattern against self; the pattern is:

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
See also #rstrip! #scrub #rstrip #scrub! also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0