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
- Enumerable({K, V})
- Iterable({K, V})
Defined in:
crystal_on_steroids/hash.crcrystal_on_steroids/to_query.cr
Instance Method Summary
-
#compact
Returns a hash with non
nil
values. -
#compact!
Replaces current hash with non
nil
values. -
#to_param
Alias for to_query
-
#to_query(namespace = nil)
Returns a string representation of the receiver suitable for use as a URL query string:
Instance methods inherited from module Enumerable({K, V})
avg
avg,
blank?
blank?,
exactly?(count : Int32, &)
exactly?,
excludes?(obj)
excludes?,
frequencies
frequencies,
many?(&)many? many?, pluck(*keys) pluck, pluck?(*keys) pluck?, without(*items) without
Instance methods inherited from class Object
in?(another_object)
in?,
presence
presence,
presence_in(another_object)
presence_in,
present?
present?,
to_param
to_param,
to_query(namespace)to_query to_query
Class methods inherited from class Object
❨╯°□°❩╯︵┻━┻
❨╯°□°❩╯︵┻━┻
Instance Method Detail
Returns a hash with non nil
values.
hash = { a: true, b: false, c: nil}
hash.compact # => { a: true, b: false }
hash # => { a: true, b: false, c: nil}
{ c: nil }.compact # => {}
source: ActiveSupport
This method is already included in Crystal, but there is a bug, so I'm keeping my own implementation of Hash#compact.
Replaces current hash with non nil
values.
hash = { a: true, b: false, c: nil }
hash.compact! # => { a: true, b: false }
hash # => { a: true, b: false }
source: Rails ActiveSupport
Returns a string representation of the receiver suitable for use as a URL query string:
{name: "David", nationality: "Danish"}.to_query
# => "name=David&nationality=Danish"
An optional namespace can be passed to enclose key names:
{name: "David", nationality: "Danish"}.to_query("user")
# => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"