Hash.include?在水晶中给出了奇怪的结果



我正在尝试编写这个Python代码的Crystal等效物:

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

这将打印 True,因为 1 是字典的键之一。

这是我尝试过的水晶代码:

# 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?在这里返回错误。为什么?我的 Python 代码的正确等价物是什么?

请改用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)

最新更新