Skip to content

Commit 3691672

Browse files
committed
🔍🔍🔍dig_hash
1 parent 0ab1c02 commit 3691672

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

dig_hash.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Hash
2+
# Dig a value of hash, by a series of keys
3+
#
4+
# info = {
5+
# order: {
6+
# customer: {
7+
# name: "Tom",
8+
# email: "[email protected]"
9+
# },
10+
# total: 100
11+
# }
12+
# }
13+
#
14+
# puts info.dig :order, :customer
15+
# # => {name: "Tom", email: "[email protected]"}
16+
#
17+
# puts info.dig :order, :customer, :name
18+
# # => "Tom"
19+
20+
def dig(*keys)
21+
keys.flatten!
22+
23+
raise if keys.empty?
24+
current_key = keys.shift
25+
current_value = self.[](current_key)
26+
27+
if keys.size == 0
28+
return current_value
29+
end
30+
31+
if current_value.is_a?(Hash)
32+
return current_value.dig(keys)
33+
else
34+
return nil
35+
end
36+
end
37+
end

0 commit comments

Comments
 (0)