Method: MatchData#named_captures
- Defined in:
- re.c
#named_captures(symbolize_names: false) ⇒ Hash
Returns a hash of the named captures; each key is a capture name; each value is its captured string or nil
:
m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
# => #<MatchData "hoge" foo:"h" bar:"ge">
m.named_captures # => {"foo"=>"h", "bar"=>"ge"}
m = /(?<a>.)(?<b>.)/.match("01")
# => #<MatchData "01" a:"0" b:"1">
m.named_captures #=> {"a" => "0", "b" => "1"}
m = /(?<a>.)(?<b>.)?/.match("0")
# => #<MatchData "0" a:"0" b:nil>
m.named_captures #=> {"a" => "0", "b" => nil}
m = /(?<a>.)(?<a>.)/.match("01")
# => #<MatchData "01" a:"0" a:"1">
m.named_captures #=> {"a" => "1"}
If keyword argument symbolize_names
is given a true value, the keys in the resulting hash are Symbols:
m = /(?<a>.)(?<a>.)/.match("01")
# => #<MatchData "01" a:"0" a:"1">
m.named_captures(symbolize_names: true) #=> {:a => "1"}
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 |
# File 're.c', line 2424
static VALUE
match_named_captures(int argc, VALUE *argv, VALUE match)
{
VALUE hash;
struct MEMO *memo;
match_check(match);
if (NIL_P(RMATCH(match)->regexp))
return rb_hash_new();
VALUE opt;
VALUE symbolize_names = 0;
rb_scan_args(argc, argv, "0:", &opt);
if (!NIL_P(opt)) {
static ID keyword_ids[1];
VALUE symbolize_names_val;
if (!keyword_ids[0]) {
keyword_ids[0] = rb_intern_const("symbolize_names");
}
rb_get_kwargs(opt, keyword_ids, 0, 1, &symbolize_names_val);
if (!UNDEF_P(symbolize_names_val) && RTEST(symbolize_names_val)) {
symbolize_names = 1;
}
}
hash = rb_hash_new();
memo = MEMO_NEW(hash, match, symbolize_names);
onig_foreach_name(RREGEXP(RMATCH(match)->regexp)->ptr, match_named_captures_iter, (void*)memo);
return hash;
}
|