File tree 2 files changed +15
-4
lines changed
2 files changed +15
-4
lines changed Original file line number Diff line number Diff line change @@ -39,7 +39,13 @@ describe "Regex::MatchData" do
39
39
40
40
it " raises if outside match range with []" do
41
41
" foo" =~ /foo/
42
- expect_raises(IndexError ) { $~ [1 ] }
42
+ expect_raises(IndexError , " Invalid capture group index: 1" ) { $~ [1 ] }
43
+ end
44
+
45
+ it " raises if special variable accessed on invalid capture group" do
46
+ " spice" =~ /spice(s) ?/
47
+ expect_raises(IndexError , " Invalid capture group index: 1" ) { $1 }
48
+ expect_raises(IndexError , " Invalid capture group index: 3" ) { $3 }
43
49
end
44
50
end
45
51
Original file line number Diff line number Diff line change @@ -129,8 +129,9 @@ class Regex
129
129
# ```
130
130
def [] (n )
131
131
check_index_out_of_bounds n
132
-
133
- self [n]?.not_nil!
132
+ value = self [n]?
133
+ raise_invalid_group_index(n) if value.nil?
134
+ value
134
135
end
135
136
136
137
# Returns the match of the capture group named by *group_name*, or
@@ -219,11 +220,15 @@ class Regex
219
220
end
220
221
221
222
private def check_index_out_of_bounds (index )
222
- raise IndexError .new unless valid_group?(index)
223
+ raise_invalid_group_index(index) unless valid_group?(index)
223
224
end
224
225
225
226
private def valid_group? (index )
226
227
index <= @size
227
228
end
229
+
230
+ private def raise_invalid_group_index (index )
231
+ raise IndexError .new(" Invalid capture group index: #{ index } " )
232
+ end
228
233
end
229
234
end
You can’t perform that action at this time.
0 commit comments