Hash
Hashes are typically created with a hash literal denoted by curly braces ({ }
) enclosing a list of pairs using =>
as delimiter between key and value and separated by commas ,
.
The generic type arguments for keys K
and values V
are inferred from the types of the keys or values inside the literal, respectively. When all have the same type, K
/V
equals to that. Otherwise it will be a union of all key types or value types respectively.
Empty hash literals always need type specifications:
{} of Int32 => Int32 # => Hash(Int32, Int32).new
Hash-like Type Literal
Crystal supports an additional literal for hashes and hash-like types. It consists of the name of the type followed by a list of comma separated key-value pairs enclosed in curly braces ({}
).
For a non-generic type like HTTP::Headers
, this is equivalent to:
headers = HTTP::Headers.new
For a generic type, the generic types are inferred from the types of the keys and values in the same way as with the hash literal.
my_hash = MyHash(typeof("foo", "bar"), typeof(1, "baz")).new
my_hash["foo"] = 1
my_hash["bar"] = "baz"
The type arguments can be explicitly specified as part of the type name: