Skip to content

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

instance method

Data#deconstruct_keys

(?::Array[::Symbol]?) -> ::Hash[::Symbol, untyped]
deconstruct_keys(array_of_names_or_nil) → hash

Returns a hash of the name/value pairs, to use in pattern matching.

Example
Measure = Data.define(:amount, :unit)

distance = Measure[10, 'km']
distance.deconstruct_keys(nil) #=> {amount: 10, unit: "km"}
distance.deconstruct_keys([:amount]) #=> {amount: 10}

# usage
case distance
in amount:, unit: 'km' # calls #deconstruct_keys underneath
  puts "It is #{amount} kilometers away"
else
  puts "Don't know how to handle it"
end
# prints "It is 10 kilometers away"

Or, with checking the class, too:

Example
case distance
in Measure(amount:, unit: 'km')
  puts "It is #{amount} kilometers away"
# ...
end
See also #deconstruct #eql? #== #hash also in 4.0 · 3.4 · 3.3 · 3.2