instance method
Hash#dig
(K, *untyped) -> untyped
dig(key, *identifiers) → object
hash.c
View on GitHub ↗
static VALUE
rb_hash_dig(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
self = rb_hash_aref(self, *argv);
if (!--argc) return self;
++argv;
return rb_obj_dig(argc, argv, self, Qnil);
}
Finds and returns an object found in nested objects, as specified by key and identifiers.
The nested objects may be instances of various classes. See Dig Methods.
Nested hashes:
Example
h = {foo: {bar: {baz: 2}}} h.dig(:foo) # => {bar: {baz: 2}} h.dig(:foo, :bar) # => {baz: 2} h.dig(:foo, :bar, :baz) # => 2 h.dig(:foo, :bar, :BAZ) # => nil
Nested hashes and arrays:
Example
h = {foo: {bar: [:a, :b, :c]}} h.dig(:foo, :bar, 2) # => :c
If no such object is found, returns the hash default:
Example
h = {foo: {bar: [:a, :b, :c]}} h.dig(:hello) # => nil h.default_proc = -> (hash, _key) { hash } h.dig(:hello, :world) # => {:foo=>{:bar=>[:a, :b, :c]}}
Related: Methods for Fetching.