Skip to content

Instantly share code, notes, and snippets.

@glucero
Created December 7, 2015 19:10
Show Gist options
  • Save glucero/5b8d4157758ce1fc819d to your computer and use it in GitHub Desktop.
Save glucero/5b8d4157758ce1fc819d to your computer and use it in GitHub Desktop.
class Hash
def to_proc
method(:[]).to_proc
end
def dig(*keys)
result = fetch(keys.shift, nil)
if result.is_a?(Hash) && keys.any?
result.dig *keys
else
result
end
end
end
@glucero
Copy link
Author

glucero commented Dec 7, 2015

hash = {a: {b: {c: {d: {one: 1, two: 2, three: 3}}}}}
> %i[one three].map &hash.dig(*%i[a b c d])
=> [
    [0] 1,
    [1] 3
]
> %i[these keys do not exist].map &hash.dig(*%i[a b c d])
=> [
    [0] nil,
    [1] nil,
    [2] nil,
    [3] nil,
    [4] nil
]
> %i[one three].map &hash.dig(*%i[this branch does not exist])
=> [
    [0] nil,
    [1] nil
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment