Hash.includes?在 crystal 中给出奇怪的结果

Hash.includes? gives weird result in crystal

我正在尝试编写与此 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? returns这里是错误的。为什么?我的 Python 代码的正确等价物是什么?

改用has_key?has_key? 询问哈希是否有那个键。

但是,includes? 检查某个 key/value 对是否在散列 table 中。如果您只提供密钥,它将始终 return 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)