Suppose a string may contain a phone number and you need its parts. A regular expression describes the pattern; `match` tests the string against it. Both regexp and string objects respond to `match`. A successful call returns a `MatchData` object; a failed call returns `nil`. section 11.2.2 section 11.4.2
Keep the result when you need more than a yes-or-no answer. `MatchData#string` retrieves the original string, `m[0]` the entire matched portion, and `m.captures` the substrings matched by parenthesized groups. Numbered indexes such as `m[1]` also retrieve captures. section 11.4.2
Listing 11.1 Matching a phone number and querying the resulting MatchData object
string = "My phone number is (123) 555-1234."
phone_re = %r{\((\d{3})\)\s+(\d{3})-(\d{4})}
m = phone_re.match(string)
unless m
puts "There was no match—sorry."
exit #1
end
print "The whole string we started with: "
puts m.string 1
print "The entire part of the string that matched: "
puts m[0] 2
puts "The three captures: "
3.times do |index| 3
puts "Capture ##{index + 1}: #{m.captures[index]}"
end
puts "Here's another way to get at the first capture:"
print "Capture #1: "
puts m[1] 4
The phone-number example saves the result, checks for failure, then retrieves the whole match and its three captures. section 11.4.2
Test and save a match together
`if m = /la/.match(name)` enters the branch only when a match succeeds. Inside it, `m.pre_match` and `m.post_match` retrieve the text before and after the match. On failure, `m` is `nil`, so querying it outside a successful branch would be unsafe. section 6.1.2 section 13.2.1
Use `match?` instead when only a Boolean is needed. The `=~` operator is another way to test a string against a regexp and can return the match position. Because a successful `MatchData` is truthy, `match` also works as a collection-filter condition, as in `array.find_all { |e| e.size > 10 and /\d/.match(e) }`. Preserve the `nil`-on-failure behavior rather than redefining `Regexp#match` globally: other code may depend on it. section 11.2.2 section 11.7 section 13.2.1

