在Crystal语言中,Hash.includes?会给出奇怪的结果。

3
我正在尝试编写与此Python代码等效的Crystal代码:

test_hash = {}
test_hash[1] = 2
print(1 in test_hash)

这段代码会输出True,因为1是字典中的一个键。

下面是我尝试过的Crystal代码:

# Create new Hash
test_hash = Hash(Int32, Int32).new
# Map 1 to 2
test_hash[1] = 2
# Check if the Hash includes 1
pp! test_hash.includes?(1)

但是在这里,includes?返回false。为什么?我的Python代码的正确等价物是什么?
1个回答

5
使用has_key?代替。 has_key?询问哈希是否具有该键。
但是,includes?检查哈希表中是否存在某个键/值对。 如果您只提供键,则始终返回false。
例子:
# Create new Hash
test_hash = Hash(Int32, Int32).new
# Map 1 to 2
test_hash[1] = 2
# Check if the Hash includes 1
pp! test_hash.has_key?(1)
# Check if the Hash includes 1 => 2
pp! test_hash.includes?({1, 2})


# Pointless, do not use
pp! test_hash.includes?(1)

你如何在键/值对都存在的情况下使用 includes??这里感觉有些不对劲... - rogerdpack
@rogerdpack: "你会如何使用includes?"并不重要。 includes?({K,V})是因为HashEnumerable<{K,V}>的结果。 Hash能够被枚举是非常棒的事情,即使我从未使用过Hash#includes?,我仍可能使用Hash#eachHash#group_by或其他任何出色的工具。 - Amadan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接