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
hash.c
View on GitHub ↗
static VALUE
rb_hash_initialize(int argc, VALUE *argv, VALUE hash)
{
VALUE ifnone;
rb_hash_modify(hash);
if (rb_block_given_p()) {
rb_check_arity(argc, 0, 0);
ifnone = rb_block_proc();
SET_PROC_DEFAULT(hash, ifnone);
}
else {
rb_check_arity(argc, 0, 1);
ifnone = argc == 0 ? Qnil : argv[0];
RHASH_SET_IFNONE(hash, ifnone);
}
return 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"