Search code examples
crystal-lang

Hash.includes? gives weird result in crystal


I'm trying to write the Crystal equivalent of this Python code:

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

This prints True, because 1 is one of the keys of the dict.

Here's the Crystal code that I've tried:

# 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)

But includes? returns false here. Why? What's the correct equivalent of my Python code?


Solution

  • Use has_key? instead. has_key? asks if the Hash has that key.

    However, includes? checks if a certain key/value pair is in the hash table. If you supply just the key, it will always return false.

    Example:

    # 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)