Skip to content

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

instance method

Data#deconstruct

deconstruct → array

Returns the values in self as an array, to use in pattern matching:

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

distance = Measure[10, 'km']
distance.deconstruct #=> [10, "km"]

# usage
case distance
in n, 'km' # calls #deconstruct underneath
  puts "It is #{n} 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(n, 'km')
  puts "It is #{n} kilometers away"
# ...
end
See also #== #deconstruct_keys .new #eql? also in 4.1 · 4.0 · 3.4 · 3.2