Skip to content

Commit

Permalink
add #dig to Array,Hash and Struct
Browse files Browse the repository at this point in the history
  • Loading branch information
matz committed Mar 23, 2016
1 parent 4c1ce0f commit daf8394
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
17 changes: 17 additions & 0 deletions mrbgems/mruby-array-ext/mrblib/array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -744,4 +744,21 @@ def index(val=NONE, &block)
def to_ary
self
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
17 changes: 17 additions & 0 deletions mrbgems/mruby-hash-ext/mrblib/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -365,4 +365,21 @@ def >=(hash)
key?(key) and self[key] == val
}
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
17 changes: 17 additions & 0 deletions mrbgems/mruby-struct/mrblib/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,22 @@ def inspect
#
alias to_s inspect
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

1 comment on commit daf8394

@zzak
Copy link
Contributor

@zzak zzak commented on daf8394 Mar 23, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/cc #3140

Please sign in to comment.