End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Hash#default
hash.default → object
hash.default(key) → object
hash.c
View on GitHub ↗
static VALUE
rb_hash_default(int argc, VALUE *argv, VALUE hash)
{
VALUE ifnone;
rb_check_arity(argc, 0, 1);
ifnone = RHASH_IFNONE(hash);
if (FL_TEST(hash, RHASH_PROC_DEFAULT)) {
if (argc == 0) return Qnil;
return call_default_proc(ifnone, hash, argv[0]);
}
return ifnone;
}
Returns the default value for the given key. The returned value will be determined either by the default proc or by the default value. See Default Values.
With no argument, returns the current default value:
Example
h = {} h.default # => nil
If key is given, returns the default value for key, regardless of whether that key exists:
Example
h = Hash.new { |hash, key| hash[key] = "No key #{key}"} h[:foo] = "Hello" h.default(:foo) # => "No key foo"
See also
#default=
#deconstruct_keys
#compare_by_identity?
#default_proc
also in
4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1