Skip to content

class Crystal::HashStringType
inherits Hash

Class methods

.new(default_value : V, initial_capacity = nil)

Creates a new empty Hash where the default_value is returned if a key is missing.

inventory = Hash(String, Int32).new(0)
inventory["socks"] = 3
inventory["pickles"] # => 0

Note

The default value is passed by reference:

arr = [1, 2, 3]
hash = Hash(String, Array(Int32)).new(arr)
hash["3"][1] = 4
arr # => [1, 4, 3]

The initial_capacity is useful to avoid unnecessary reallocations of the internal buffer in case of growth. If the number of elements a hash will hold is known, the hash should be initialized with that capacity for improved performance. Otherwise, the default is 8. Inputs lower than 8 are ignored.

View source

.new(pull : JSON::PullParser)

Reads a Hash from the given pull parser.

Keys are read by invoking from_json_object_key? on this hash's key type (K), which must return a value of type K or nil. If nil is returned a JSON::ParseException is raised.

Values are parsed using the regular new(pull : JSON::PullParser) method.

View source

.new

Creates a new empty Hash.

View source

.new(block : Hash(K, V), K -> V? = nil, *, initial_capacity = nil)

Creates a new empty Hash with a block for handling missing keys.

proc = ->(hash : Hash(String, Int32), key : String) { hash[key] = key.size }
hash = Hash(String, Int32).new(proc)

hash.size   # => 0
hash["foo"] # => 3
hash.size   # => 1
hash["bar"] = 10
hash["bar"] # => 10

The initial_capacity is useful to avoid unnecessary reallocations of the internal buffer in case of growth. If the number of elements a hash will hold is known, the hash should be initialized with that capacity for improved performance. Otherwise, the default is 8. Inputs lower than 8 are ignored.

View source

.new(initial_capacity = nil, &block : Hash(K, V), K -> V)

Creates a new empty Hash with a block that handles missing keys.

hash = Hash(String, Int32).new do |hash, key|
  hash[key] = key.size
end

hash.size   # => 0
hash["foo"] # => 3
hash.size   # => 1
hash["bar"] = 10
hash["bar"] # => 10

The initial_capacity is useful to avoid unnecessary reallocations of the internal buffer in case of growth. If the number of elements a hash will hold is known, the hash should be initialized with that capacity for improved performance. Otherwise, the default is 8. Inputs lower than 8 are ignored.

View source

Methods

#to_json(json : JSON::Builder)

Serializes this Hash into JSON.

Keys are serialized by invoking to_json_object_key on them. Values are serialized with the usual to_json(json : JSON::Builder) method.

View source