Skip to content

Commit

Permalink
MatchData: raise KeyError instead of ArgumentError
Browse files Browse the repository at this point in the history
Currently #[](key: String) raises `ArgumentError`. I think it should
raise `KeyError` because it looks like `Hash` operation.
makenowjust authored and asterite committed Jun 12, 2017
1 parent 61f21ae commit 5fb0438
Showing 2 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion spec/std/match_data_spec.cr
Original file line number Diff line number Diff line change
@@ -34,7 +34,7 @@ describe "Regex::MatchData" do

it "raises exception when named group doesn't exist" do
("foo" =~ /foo/).should eq(0)
expect_raises(ArgumentError) { $~["group"] }
expect_raises(KeyError) { $~["group"] }
end

it "raises if outside match range with []" do
6 changes: 3 additions & 3 deletions src/regex/match_data.cr
Original file line number Diff line number Diff line change
@@ -148,16 +148,16 @@ class Regex
end

# Returns the match of the capture group named by *group_name*, or
# raises an `ArgumentError` if there is no such named capture group.
# raises an `KeyError` if there is no such named capture group.
#
# ```
# "Crystal".match(/r(?<ok>ys)/).not_nil!["ok"] # => "ys"
# "Crystal".match(/r(?<ok>ys)/).not_nil!["ng"] # raises ArgumentError
# "Crystal".match(/r(?<ok>ys)/).not_nil!["ng"] # raises KeyError
# ```
def [](group_name : String)
match = self[group_name]?
unless match
raise ArgumentError.new("Match group named '#{group_name}' does not exist")
raise KeyError.new("Match group named '#{group_name}' does not exist")
end
match
end

0 comments on commit 5fb0438

Please sign in to comment.