instance method · added in Ruby 3.2
Time#deconstruct_keys
(::Array[::Symbol]?) -> ::Hash[::Symbol, ::Integer]
deconstruct_keys(array_of_names_or_nil) → hash
time.c
View on GitHub ↗
static VALUE
time_deconstruct_keys(VALUE time, VALUE keys)
{
struct time_object *tobj;
VALUE h;
long i;
GetTimeval(time, tobj);
MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
if (NIL_P(keys)) {
h = rb_hash_new_with_size(11);
rb_hash_aset(h, sym_year, tobj->vtm.year);
rb_hash_aset(h, sym_month, INT2FIX(tobj->vtm.mon));
rb_hash_aset(h, sym_day, INT2FIX(tobj->vtm.mday));
rb_hash_aset(h, sym_yday, INT2FIX(tobj->vtm.yday));
rb_hash_aset(h, sym_wday, INT2FIX(tobj->vtm.wday));
rb_hash_aset(h, sym_hour, INT2FIX(tobj->vtm.hour));
rb_hash_aset(h, sym_min, INT2FIX(tobj->vtm.min));
rb_hash_aset(h, sym_sec, INT2FIX(tobj->vtm.sec));
rb_hash_aset(h, sym_subsec,
quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
rb_hash_aset(h, sym_dst, RBOOL(tobj->vtm.isdst));
rb_hash_aset(h, sym_zone, time_zone(time));
return h;
}
if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
rb_raise(rb_eTypeError,
"wrong argument type %"PRIsVALUE" (expected Array or nil)",
rb_obj_class(keys));
}
h = rb_hash_new_with_size(RARRAY_LEN(keys));
for (i=0; i<RARRAY_LEN(keys); i++) {
VALUE key = RARRAY_AREF(keys, i);
if (sym_year == key) rb_hash_aset(h, key, tobj->vtm.year);
if (sym_month == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mon));
if (sym_day == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mday));
if (sym_yday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.yday));
if (sym_wday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.wday));
if (sym_hour == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.hour));
if (sym_min == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.min));
if (sym_sec == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.sec));
if (sym_subsec == key) {
rb_hash_aset(h, key, quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
}
if (sym_dst == key) rb_hash_aset(h, key, RBOOL(tobj->vtm.isdst));
if (sym_zone == key) rb_hash_aset(h, key, time_zone(time));
}
return h;
}
Returns a hash of the name/value pairs, to use in pattern matching. Possible keys are: :year, :month, :day, :yday, :wday, :hour, :min, :sec, :subsec, :dst, :zone.
Possible usages:
Example
t = Time.utc(2022, 10, 5, 21, 25, 30) if t in wday: 3, day: ..7 # uses deconstruct_keys underneath puts "first Wednesday of the month" end #=> prints "first Wednesday of the month" case t 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 t in Time(wday: 3, day: ..7) puts "first Wednesday of the month" end
Ruby version changes
-
3.2
-
Time#deconstruct_keysis added, allowing to useTimeinstances in pattern-matching expressions [Feature #19071]
-