Skip to content

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

instance method

Date#deconstruct_keys

deconstruct_keys(array_of_names_or_nil) → hash

Returns a hash of the name/value pairs, to use in pattern matching. Possible keys are: :year, :month, :day, :wday, :yday.

Possible usages:

Example
d = Date.new(2022, 10, 5)

if d in wday: 3, day: ..7  # uses deconstruct_keys underneath
  puts "first Wednesday of the month"
end
#=> prints "first Wednesday of the month"

case d
in year: ...2022
  puts "too old"
in month: ..9
  puts "quarter 1-3"
in wday: 1..5, month:
  puts "working day in month #{month}"
end
#=> prints "working day in month 10"

Note that deconstruction by pattern can also be combined with class check:

Example
if d in Date(wday: 3, day: ..7)
  puts "first Wednesday of the month"
end
See also #day_fraction #downto #day #england also in 4.1 · 4.0 · 3.4 · 3.2