MatchData#captures returns an array containing the substrings matched by a regular expression’s parenthesized capture groups. For a phone-number match, the array contains "123", "555", and "1234". section 11.4.2
Extracting phone-number parts
phone_re = %r{\((\d{3})\)\s+(\d{3})-(\d{4})} m = phone_re.match("My phone number is (123) 555-1234.") m.captures # => ["123", "555", "1234"] The array is zero-based, so m.captures[0] is the first capture. section 11.4.3
Use captures alongside MatchData indexing when extracting or interpreting matched substrings:
- m[0] returns the entire matched substring; m[1] returns the first parenthesized capture. section 11.4.2
- m[1] == m.captures[0] and m[2] == m.captures[1]; indexing MatchData counts captures from 1, while the returned array counts from 0. section 11.4.3
- Capture numbers follow opening parentheses from left to right, including nested groups; negative MatchData indexes retrieve captures from the end. section 11.4.3
