Skip to content
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(pattern) → array_of_results
scan(pattern) {|result| ... } → self

Matches a pattern against self:

Generates a collection of matching results and updates regexp-related global variables:

  • If the pattern contains no groups, each result is a matched substring.

  • If the pattern contains groups, each result is an array containing a matched substring for each group.

With no block given, returns an array of the results:

Example
'cruel world'.scan(/\w+/)      # => ["cruel", "world"]
'cruel world'.scan(/.../)      # => ["cru", "el ", "wor"]
'cruel world'.scan(/(...)/)    # => [["cru"], ["el "], ["wor"]]
'cruel world'.scan(/(..)(..)/) # => [["cr", "ue"], ["l ", "wo"]]
'тест'.scan(/../)              # => ["те", "ст"]
'こんにちは'.scan(/../)         # => ["こん", "にち"]
'abracadabra'.scan('ab')       # => ["ab", "ab"]
'abracadabra'.scan('nosuch')   # => []

With a block given, calls the block with each result; returns self:

Example
'cruel world'.scan(/\w+/) {|w| p w }
# => "cruel"
# => "world"
'cruel world'.scan(/(.)(.)/) {|x, y| p [x, y] }
# => ["c", "r"]
# => ["u", "e"]
# => ["l", " "]
# => ["w", "o"]
# => ["r", "l"]

Related: see Converting to Non-String.

See also #rstrip! #scrub #rstrip #scrub! also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0