Regexp

If the integer nth is 0, returns the matching string ($&). Otherwise, returns the substring matching the nth set of parentheses ($1, $2, ...). When there are no corresponding parentheses or no matches, returns nil.

/(.)(.)/ =~ "ab"
p Regexp.last_match      # => #<MatchData:0x4599e58>
p Regexp.last_match(0)   # => "ab"
p Regexp.last_match(1)   # => "a"
p Regexp.last_match(2)   # => "b"
p Regexp.last_match(3)   # => nil

Because Regexp.last_match, with no arguments, returns nil when the entire regular expression does not match, the format last_match[1] will throw a NameError exception. On the other hand, last_match(1) returns nil.

Last updated