Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Regexp#named_captures

() -> ::Hash[::String, ::Array[::Integer]]
named_captures → hash

Returns a hash representing named captures of self (see Named Captures):

  • Each key is the name of a named capture.

  • Each value is an array of integer indexes for that named capture.

Examples:

Example
/(?<foo>.)(?<bar>.)/.named_captures # => {"foo"=>[1], "bar"=>[2]}
/(?<foo>.)(?<foo>.)/.named_captures # => {"foo"=>[1, 2]}
/(.)(.)/.named_captures             # => {}
See also #match? #names #match #options also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0