Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
Hash.new
# File tmp/rubies/ruby-3.4.1/hash.rb, line 37
def initialize(ifnone = (ifnone_unset = true), capacity: 0, &block)
Primitive.rb_hash_init(capacity, ifnone_unset, ifnone, block)
end
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:
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:
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:
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
-
3.4
-
Hash.newnow accepts an optionalcapacity: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]
-