From 29862685c0acf3a40c6b1f9e8780cbbd86cba658 Mon Sep 17 00:00:00 2001 From: nobu Date: Mon, 9 Nov 2015 12:27:26 +0000 Subject: dig * array.c (rb_ary_dig): new method Array#dig. * hash.c (rb_hash_dig): new method Hash#dig. * object.c (rb_obj_dig): dig in nested arrays/hashes. [Feature #11643] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@52504 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- hash.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'hash.c') diff --git a/hash.c b/hash.c index c179ff4ce1..ae65aa4a1e 100644 --- a/hash.c +++ b/hash.c @@ -2691,6 +2691,29 @@ rb_hash_any_p(VALUE hash) return ret; } +/* + * call-seq: + * hsh.dig(key, ...) -> object + * + * Retrieves the value object corresponding to the each key + * objects repeatedly. + * + * h = { foo: {bar: {baz: 1}}} + * + * h.dig(:foo, :bar, :baz) #=> 1 + * h.dig(:foo, :zot) #=> nil + */ + +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); +} + static int path_tainted = -1; static char **origenviron; @@ -4114,6 +4137,7 @@ Init_Hash(void) rb_define_method(rb_cHash,"compare_by_identity?", rb_hash_compare_by_id_p, 0); rb_define_method(rb_cHash, "any?", rb_hash_any_p, 0); + rb_define_method(rb_cHash, "dig", rb_hash_dig, -1); /* Document-class: ENV * -- cgit v1.2.3