class Hash(K, V)
- Hash(K, V)
- Reference
- Object
Overview
A Hash
represents a collection of key-value mappings, similar to a dictionary.
Main operations are storing a key-value mapping (#[]=
) and
querying the value associated to a key (#[]
). Key-value mappings can also be
deleted (#delete
).
Keys are unique within a hash. When adding a key-value mapping with a key that
is already in use, the old value will be forgotten.
# Create a new Hash for mapping String to Int32
hash = Hash(String, Int32).new
hash["one"] = 1
hash["two"] = 2
hash["one"] # => 1
Hash literals
can also be used to create a Hash
:
{"one" => 1, "two" => 2}
Implementation is based on an open hash table.
Two objects refer to the same hash key when their hash value (Object#hash
)
is identical and both objects are equal to each other (Object#==
).
Enumeration follows the order that the corresponding keys were inserted.
NOTE When using mutable data types as keys, changing the value of a key after
it was inserted into the Hash
may lead to undefined behaviour. This can be
restored by re-indexing the hash with #rehash
.
Included Modules
- Collection(K, V)
- Digable(K)
- Enumerable({K, V})
- Iterable({K, V})
Defined in:
collection/core_ext.crInstance Method Summary
-
#each_pair(&) : Nil
Must yield this structure's key, value or index, element pairs.
-
#each_pair : Iterator(Tuple(K, V))
Provides an
Iterator
for each pair inself
. -
#traverse(*prefix : *T, &) : Nil forall T
Traverse the structure depth first yielding a tuple of the path through the structure and the leaf value for every element to the passed block.
-
#traverse(*prefix : *T) : Iterator forall T
Provide an iterator that may be used to traverse a nested structure.
Instance methods inherited from module Collection(K, V)
[](key_or_index : X) : Y
[],
[]?(key_or_index : X) : Y | Nil
[]?,
dig(key : X, *subkeys)
dig,
dig?(key : X, *subkeys)
dig?,
each_pair(&block : Tuple(X, Y) -> ) : Nileach_pair : Iterator(Tuple(X, Y)) each_pair, nested? : Bool nested?
Instance methods inherited from class Object
presence
presence
Instance Method Detail
Must yield this structure's key, value or index, element pairs.
Provides an Iterator
for each pair in self
.
NOTE when the base collection provides it own iterator implementation, this method should be overridden to use this directly, this is a generalised implementation and likely sub-optimal in many cases.
Traverse the structure depth first yielding a tuple of the path through the structure and the leaf value for every element to the passed block.
The paths contain a tuple of the keys or indicies used across
intermediate structures, similar to what would be passed to #dig
.
Provide an iterator that may be used to traverse a nested structure.