Method: MatchData#deconstruct_keys
- Defined in:
- re.c
#deconstruct_keys(array_of_names) ⇒ Hash
Returns a hash of the named captures for the given names.
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:
m = /(\d{2}):(\d{2}):(\d{2})/.match("18:37:22")
m.deconstruct_keys(nil) # => {}
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 |
# File 're.c', line 2477
static VALUE
match_deconstruct_keys(VALUE match, VALUE keys)
{
VALUE h;
long i;
match_check(match);
if (NIL_P(RMATCH(match)->regexp)) {
return rb_hash_new_with_size(0);
}
if (NIL_P(keys)) {
h = rb_hash_new_with_size(onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)));
struct MEMO *memo;
memo = MEMO_NEW(h, match, 1);
onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, (void*)memo);
return h;
}
Check_Type(keys, T_ARRAY);
if (onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)) < RARRAY_LEN(keys)) {
return rb_hash_new_with_size(0);
}
h = rb_hash_new_with_size(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 = NAME_TO_NUMBER(RMATCH_REGS(match), RMATCH(match)->regexp, RMATCH(match)->regexp,
RSTRING_PTR(name), RSTRING_END(name));
if (num >= 0) {
rb_hash_aset(h, key, rb_reg_nth_match(num, match));
}
else {
return h;
}
}
return h;
}
|