Skip to content

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

instance method

MatchData#named_captures

mtch.named_captures → hash

Returns a Hash using named capture.

A key of the hash is a name of the named captures. A value of the hash is a string of last successful capture of corresponding group.

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

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

m = /(?<a>.)(?<a>.)/.match("01")
m.named_captures #=> {"a" => "1"}

m = /(?<a>x)|(?<a>y)/.match("x")
m.named_captures #=> {"a" => "x"}
See also #length #names #inspect #offset also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1