Intro

Hashes in Crystal are a collection of key/value pairs of defined types.

Creating a hash

crystal
# Create a hash with strings for keys and values.
stuff_and_things = {
    "stuff" => "stuff",
    "things" => "things",
}

# Deduce the type signature of a hash. 
typeof(stuff_and_things) # => Hash(String, String)

# To create an empty hash, you must define 
# the intended type of its key/value pairs.
# There are 2 ways to define an empty hash.
stuff_and_things = {} of String => String
stuff_and_things = Hash(String, String).new

Iterating a Hash

crystal
# Iterate through a hash
stuff_and_things.each do |key, value|
  puts "#{key} #{value}"
end

Accessing Elements

crystal
# Get a value via the key name
stuff_and_things["stuff"]

# There are 2 ways to check if a key exists
stuff_and_things["stuff"]? # => value or nil
stuff_and_things.has_key?("stuff") # => true or false

# Check if a value exists
stuff_and_things.has_value?("stuff") # => true or false

Hash Operations

crystal
# Add key/value pair to a hash
stuff_and_things["blah"] = "blah"

# Change the value of the "blah" key
stuff_and_things["blah"] = "blahblah"

# Delete the "stuff" key
stuff_and_things.delete("stuff")

# Get the size of a hash
stuff_and_things.size # => 3

Considerations

  • Keys are unique within a hash.
  • Elements maintain their insertion order.
  • Attempting to access a key of a hash that does not exist is a runtime error.