Skip to content

Commit fb543d0

Browse files
committed
named_captures: fix incompatibility with MatchData#named_captures
Fix GH-145 `MatchData#named_captures` use the last matched value for each name. Reported by Linus Sellberg. Thanks!!!
1 parent 4aadfc8 commit fb543d0

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

ext/strscan/strscan.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2211,7 +2211,10 @@ named_captures_iter(const OnigUChar *name,
22112211
VALUE value = RUBY_Qnil;
22122212
int i;
22132213
for (i = 0; i < back_num; i++) {
2214-
value = strscan_aref(data->self, INT2NUM(back_refs[i]));
2214+
VALUE v = strscan_aref(data->self, INT2NUM(back_refs[i]));
2215+
if (!RB_NIL_P(v)) {
2216+
value = v;
2217+
}
22152218
}
22162219
rb_hash_aset(data->captures, key, value);
22172220
return 0;

test/strscan/test_stringscanner.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -967,6 +967,12 @@ def test_named_captures
967967
assert_equal({}, scan.named_captures)
968968
end
969969

970+
def test_named_captures_same_name_union
971+
scan = StringScanner.new("123")
972+
assert_equal(1, scan.match?(/(?<number>0)|(?<number>1)|(?<number>2)/))
973+
assert_equal({"number" => "1"}, scan.named_captures)
974+
end
975+
970976
def test_scan_integer
971977
s = create_string_scanner('abc')
972978
assert_equal(3, s.match?(/(?<a>abc)/)) # set named_captures

0 commit comments

Comments
 (0)