instance method
MatchData#named_captures
() -> ::Hash[::String, ::String?]
(symbolize_names: true) -> ::Hash[::Symbol, ::String?]
(symbolize_names: ::boolish) -> ::Hash[::String | ::Symbol, ::String?]
named_captures(symbolize_names: false) → hash
re.c
View on GitHub ↗
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;
}
Returns a hash of the named captures; each key is a capture name; each value is its captured string or nil:
Example
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:
Example
m = /(?<a>.)(?<a>.)/.match("01") # => #<MatchData "01" a:"0" a:"1"> m.named_captures(symbolize_names: true) #=> {:a => "1"}
Ruby version changes
-
3.3
-
MatchData#named_capturesnow accepts optionalsymbolize_nameskeyword. [Feature #19591]
-