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

尼克·奥德尔

我正在尝试编写与此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代码的正确等效项是什么?

尼克·奥德尔

使用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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章