Skip to content
instance method

MatchData#named_captures

() -> ::Hash[::String, ::String?]
(symbolize_names: true) -> ::Hash[::Symbol, ::String?]
(symbolize_names: ::boolish) -> ::Hash[::String | ::Symbol, ::String?]
named_captures(symbolize_names: false) → 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"}

If keyword argument symbolize_names is given a true value, the keys in the resulting hash are Symbols:

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

Ruby version changes

  1. 3.3
See also #match_length #names #match #offset also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0