Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
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:
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:
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:
h = Hash.new {|hash, key| "Default value for #{key}" }
h.default # => nil
h.default_proc.class # => Proc
h[:nosuch] # => "Default value for nosuch"
 
               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;
}
            

Was this page useful?