Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Hash.new

Hash.new(default_value = nil) → new_hash
Hash.new {|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 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 given but no block 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 given but no argument, 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"
See also .[] .ruby2_keywords_hash .ruby2_keywords_hash? also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0