Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method · added in Ruby 3.2
MatchData#deconstruct_keys
(::Array[::Symbol]? array_of_names) -> ::Hash[::Symbol, ::String?]
deconstruct_keys(array_of_names) → hash
re.c
View on GitHub ↗
static VALUE
match_deconstruct_keys(VALUE match, VALUE keys)
{
VALUE h;
rb_len_t i;
match_check(match);
if (NIL_P(RMATCH(match)->regexp)) {
return rb_hash_new();
}
if (NIL_P(keys)) {
h = rb_hash_new_capa(onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)));
struct named_captures_data data = { h, match, 1 };
onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, &data);
return h;
}
Check_Type(keys, T_ARRAY);
if (onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)) < RARRAY_LEN(keys)) {
return rb_hash_new();
}
h = rb_hash_new_capa(RARRAY_LEN(keys));
for (i=0; i<RARRAY_LEN(keys); i++) {
VALUE key = RARRAY_AREF(keys, i);
VALUE name;
Check_Type(key, T_SYMBOL);
name = rb_sym2str(key);
int num = match_name_to_backref_number(match, name);
if (num >= 0) {
rb_hash_aset(h, key, rb_reg_nth_match(num, match));
}
else {
return h;
}
}
return h;
}
Returns a hash of the named captures for the given names.
Example
m = /(?<hours>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})/.match("18:37:22") m.deconstruct_keys([:hours, :minutes]) # => {:hours => "18", :minutes => "37"} m.deconstruct_keys(nil) # => {:hours => "18", :minutes => "37", :seconds => "22"}
Returns an empty hash if no named captures were defined:
Example
m = /(\d{2}):(\d{2}):(\d{2})/.match("18:37:22") m.deconstruct_keys(nil) # => {}
Ruby version changes
-
3.2
-
MatchData#deconstruct_keyshas been added. [Feature #18821]
-