Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Hash.new

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

Returns a new empty Hash object.

The initial default value and initial default proc for the new hash depend on which form above was used. See Default Values.

If neither an argument nor a block is given, initializes both the default value and the default proc to nil:

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

If argument default_value is given but no block is given, initializes the default value to the given default_value and the default proc to nil:

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

If a block is given but no default_value, stores the block as the default proc and sets the default value to nil:

Example
h = Hash.new {|hash, key| "Default value for #{key}" }
h.default # => nil
h.default_proc.class # => Proc
h[:nosuch] # => "Default value for nosuch"

If both a block and a default_value are given, raises an ArgumentError

If the optional keyword argument capacity is given, the hash will be allocated with enough capacity to accommodate this many keys without having to be resized.

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 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0