Skip to content
instance method

MatchData#[]

(::MatchData::capture backref, ?nil) -> ::String?
(::int start, ::int length) -> ::Array[::String?]
(::range[::int?] range) -> ::Array[::String?]
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"

If multiple captures have the same name, returns the last matched substring.

Example
m = /(?<foo>.)(?<foo>.+)/.match("hoge")
# => #<MatchData "hoge" foo:"h" foo:"oge">
m[:foo] #=> "oge"

m = /\W(?<foo>.+)|\w(?<foo>.+)|(?<foo>.+)/.match("hoge")
#<MatchData "hoge" foo:nil foo:"oge" foo:nil>
m[:foo] #=> "oge"
See also #== #begin #bytebegin also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0