Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

MatchData#[]

matchdata[index] → string or nil
matchdata[start, length] → array
matchdata[range] → array
matchdata[name] → string or nil

When arguments index, +start and length, or range are given, returns match and captures in the style of Array#[]:

Example
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
# => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
m[0] # => "HX1138"
m[1, 2]  # => ["H", "X"]
m[1..3]  # => ["H", "X", "113"]
m[-3, 2] # => ["X", "113"]

When string or symbol argument name is given, returns the matched substring for the given name:

Example
m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
# => #<MatchData "hoge" foo:"h" bar:"ge">
m['foo'] # => "h"
m[:bar]  # => "ge"
See also #== #begin #byteoffset also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0