Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. 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.1 · 4.0 · 3.3 · 3.2