# irb
a = "barfoobazfoobaofoo"
#For match
a.match(/ba./)
=> #<MatchData "bar">
#For scan
a.scan(/ba./)
=> ["bar", "baz", "bao"]
match returns a MatchData
object
scan is returned as an array.
#irb
# match
a.match(/baa./)
=> nil
# scan
a.scan(/baa./)
=> []
For match, nil is returned, scan returns an empty array.
match does not return an array, so trying to loop through the results will result in an error. Since scan returns an array, it can be looped. (In other words, scan can be processed by passing the block as it is, so you can do this ↓)
# irb
a.scan(/ba./) {|s| p s*2}
"barbar"
"bazbaz"
"baobao"
Since match returns nil, it becomes false at the time of conditional branching. Note that scan is [], so it will be true in conditional branching.
https://docs.ruby-lang.org/ja/latest/method/String/i/match.html https://docs.ruby-lang.org/ja/latest/method/String/i/scan.html
Recommended Posts