MatchData
Returns the nth substring. 0 signifies the entire matching string. When the value of n is negative, it is treated as a backwards index (the final element being in the position -1). When the nth element does not exist, returns nil.
/(foo)(bar)(BAZ)?/ =~ "foobarbaz"
p $~.to_a # => ["foobar", "foo", "bar", nil]
p $~[0] # => "foobar"
p $~[1] # => "foo"
p $~[2] # => "bar"
p $~[3] # => nil (doesn't match)
p $~[4] # => nil (out of range)
p $~[-2] # => "bar"
Last updated