Hash(K, V)
Inherits Iterable < Enumerable < Reference < Object
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.
Instance methods
Returns the element for which the passed block returns with the maximum value.
It compares using > so the block must return a type that supports that method
["Alice", "Bob"].max_by { |name| name.size } # => "Alice"
Raises Enumerable::EmptyError if the collection is empty.
Returns the element for which the passed block returns with the minimum value.
It compares using < so the block must return a type that supports that method
["Alice", "Bob"].min_by { |name| name.size } # => "Bob"
Raises Enumerable::EmptyError if the collection is empty.
Adds all results of the passed block for each element in the collection.
["Alice", "Bob"].sum { |name| name.size } # => 8 (5 + 3)
Expects all types returned from the block to respond to #+ method.
This method calls .additive_identity on the yielded type to determine the
type of the sum value. Hence, it can fail to compile if
.additive_identity fails to determine a safe type, e.g., in case of
union types. In such cases, use sum(initial) with an initial value of
the expected type of the sum value.
If the collection is empty, returns additive_identity.
([] of Int32).sum { |x| x + 1 } # => 0