Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method · added in Ruby 3.2

MatchData#deconstruct_keys

(::Array[::Symbol]? array_of_names) -> ::Hash[::Symbol, ::String?]
deconstruct_keys(array_of_names) → hash

Returns a hash of the named captures for the given names.

Example
m = /(?<hours>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})/.match("18:37:22")
m.deconstruct_keys([:hours, :minutes]) # => {:hours => "18", :minutes => "37"}
m.deconstruct_keys(nil) # => {:hours => "18", :minutes => "37", :seconds => "22"}

Returns an empty hash if no named captures were defined:

Example
m = /(\d{2}):(\d{2}):(\d{2})/.match("18:37:22")
m.deconstruct_keys(nil) # => {}

Ruby version changes

  1. 3.2
See also #deconstruct #end #captures #eql? also in 4.0 · 3.4 · 3.3 · 3.2