3

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?

Nick ODell
  • 15,465
  • 3
  • 32
  • 66

1 Answers1

5

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)
Nick ODell
  • 15,465
  • 3
  • 32
  • 66
  • How would you use `includes?` with the key/value pair both there? Something doesn't feel quite right here... – rogerdpack Jul 06 '18 at 21:56
  • @rogerdpack: "How would you use `includes?`" is beside the point. `includes?({K, V})` is the consequence of `Hash` being `Enumerable<{K, V}>`. Hash being Enumerable is a very cool thing, and even if I never use `Hash#includes?` I might use `Hash#each`, `Hash#group_by` or any of the other great tools there. – Amadan Jul 18 '18 at 04:36