-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdig_hash.rb
More file actions
37 lines (33 loc) · 715 Bytes
/
dig_hash.rb
File metadata and controls
37 lines (33 loc) · 715 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Hash
# Dig a value of hash, by a series of keys
#
# info = {
# order: {
# customer: {
# name: "Tom",
# email: "tom@mail.com"
# },
# total: 100
# }
# }
#
# puts info.dig :order, :customer
# # => {name: "Tom", email: "tom@mail.com"}
#
# puts info.dig :order, :customer, :name
# # => "Tom"
def dig(*keys)
keys.flatten!
raise if keys.empty?
current_key = keys.shift
current_value = self.[](current_key)
if keys.size == 0
return current_value
end
if current_value.is_a?(Hash)
return current_value.dig(keys)
else
return nil
end
end
end