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#named_captures

named_captures → hash

Returns a hash of the named captures; each key is a capture name; each value is its captured string or nil:

Example
m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
# => #<MatchData "hoge" foo:"h" bar:"ge">
m.named_captures # => {"foo"=>"h", "bar"=>"ge"}

m = /(?<a>.)(?<b>.)/.match("01")
# => #<MatchData "01" a:"0" b:"1">
m.named_captures #=> {"a" => "0", "b" => "1"}

m = /(?<a>.)(?<b>.)?/.match("0")
# => #<MatchData "0" a:"0" b:nil>
m.named_captures #=> {"a" => "0", "b" => nil}

m = /(?<a>.)(?<a>.)/.match("01")
# => #<MatchData "01" a:"0" a:"1">
m.named_captures #=> {"a" => "1"}
See also #match_length #names #match #offset also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0