Skip to content
class method

Hash.new

[unchecked out K, unchecked out V] (?capacity: ::int) -> ::Hash[K, V]
[unchecked out K, unchecked out V] (V default, ?capacity: ::int) -> ::Hash[K, V]
[unchecked out K, unchecked out V] (?capacity: ::int) { (::Hash[K, V] hash, K key) -> V } -> ::Hash[K, V]
Hash.new(default_value = nil, capacity: 0) → new_hash
Hash.new(capacity: 0) {|self, key| ... } → new_hash

Returns a new empty Hash object.

Initializes the values of Hash#default and Hash#default_proc, which determine the behavior when a given key is not found; see Key Not Found?.

By default, a hash has nil values for both default and default_proc:

Example
h = Hash.new        # => {}
h.default           # => nil
h.default_proc      # => nil

With argument default_value given, sets the default value for the hash:

Example
h = Hash.new(false) # => {}
h.default           # => false
h.default_proc      # => nil

With a block given, sets the default_proc value:

Example
h = Hash.new {|hash, key| "Hash #{hash}: Default value for #{key}" }
h.default      # => nil
h.default_proc # => #<Proc:0x00000289b6fa7048 (irb):185>
h[:nosuch]     # => "Hash {}: Default value for nosuch"

Raises ArgumentError if both default_value and a block are given.

If optional keyword argument capacity is given with a positive integer value n, initializes the hash with enough capacity to accommodate n entries without resizing.

See also Methods for Creating a Hash.

Ruby version changes

  1. 3.4
    • Hash.new now accepts an optional capacity: argument, to preallocate the hash with a given capacity. This can improve performance when building large hashes incrementally by saving on reallocation and rehashing of keys. [Feature #19236]

See also .[] .ruby2_keywords_hash .ruby2_keywords_hash? also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0