Skip to content

Commit 034a6dc

Browse files
authored
Enhance error message for Hash#[] when key is wrong type for default block (#16442)
1 parent 1a03b8e commit 034a6dc

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

spec/std/hash_spec.cr

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,29 @@ describe "Hash" do
159159
# a[2].should raise_exception
160160
a.should eq({1 => 2})
161161
end
162+
163+
it "raises on missing key" do
164+
h = {1 => 2}
165+
166+
expect_raises KeyError, "Missing hash key: 2" do
167+
h[2]
168+
end
169+
end
170+
171+
describe "with block" do
172+
it "calls and returns if of the same type" do
173+
h = Hash(Int32, String).new { "b" }
174+
h[0].should eq("b")
175+
end
176+
177+
it "errors if of the wrong type" do
178+
h = Hash(Int32, String).new { "b" }
179+
180+
expect_raises KeyError, "Invalid key type: expected Int32, got String" do
181+
h["0"]
182+
end
183+
end
184+
end
162185
end
163186

164187
describe "[]=" do

src/hash.cr

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,8 +1192,12 @@ class Hash(K, V)
11921192
# ```
11931193
def [](key)
11941194
fetch(key) do
1195-
if (block = @block) && key.is_a?(K)
1196-
block.call(self, key.as(K))
1195+
if block = @block
1196+
unless key.is_a?(K)
1197+
raise KeyError.new "Invalid key type: expected #{K}, got #{key.class}"
1198+
end
1199+
1200+
block.call(self, key)
11971201
else
11981202
raise KeyError.new "Missing hash key: #{key.inspect}"
11991203
end

0 commit comments

Comments
 (0)