add #dig to Array,Hash and Struct

parent 4c1ce0f6
...@@ -744,4 +744,21 @@ class Array ...@@ -744,4 +744,21 @@ class Array
def to_ary def to_ary
self self
end end
##
# call-seq:
# ary.dig(idx, ...) -> object
#
# Extracts the nested value specified by the sequence of <i>idx</i>
# objects by calling +dig+ at each step, returning +nil+ if any
# intermediate step is +nil+.
#
def dig(idx,*args)
n = self[idx]
if args.size > 0
n&.dig(*args)
else
n
end
end
end end
...@@ -365,4 +365,21 @@ class Hash ...@@ -365,4 +365,21 @@ class Hash
key?(key) and self[key] == val key?(key) and self[key] == val
} }
end end
##
# call-seq:
# hsh.dig(key,...) -> object
#
# Extracts the nested value specified by the sequence of <i>key</i>
# objects by calling +dig+ at each step, returning +nil+ if any
# intermediate step is +nil+.
#
def dig(idx,*args)
n = self[idx]
if args.size > 0
n&.dig(*args)
else
n
end
end
end end
...@@ -82,5 +82,22 @@ if Object.const_defined?(:Struct) ...@@ -82,5 +82,22 @@ if Object.const_defined?(:Struct)
# #
alias to_s inspect alias to_s inspect
end end
##
# call-seq:
# hsh.dig(key,...) -> object
#
# Extracts the nested value specified by the sequence of <i>key</i>
# objects by calling +dig+ at each step, returning +nil+ if any
# intermediate step is +nil+.
#
def dig(idx,*args)
n = self[idx]
if args.size > 0
n&.dig(*args)
else
n
end
end
end end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment