published: 28th of July 2021
Hashes in Crystal are a collection of key/value pairs of defined types.
# 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
# Iterate through a hash
stuff_and_things.each do |key, value|
puts "#{key} #{value}"
end
# 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
# 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
https://pragprog.com/titles/crystal/programming-crystal/
https://crystal-lang.org/reference/syntax_and_semantics/literals/hash.html