Ruby hash.dig using array as argument?

3k views Asked by At

I have a nested hash of data

foo => {
  'user' => { 
    'address' => {
      'street' => '1234'
    }
  }
}

I can access the values using Hash.dig

foo.dig('user', 'address', 'street')
1234

How would you use hash.dig when the values are variable, and are defined in an array?

query=["users", "address", "street"]
  
foo.dig(query) # <= doesn't work  
foo.dig(query.to_s) # <= doesn't work  

Looking at the ruby docs, Hash.dig appears to take multiple parameters, but does not take an array

https://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig

2

There are 2 answers

1
Oleksandr Holubenko On BEST ANSWER

You can do it with a splat operator to split up an array into an argument list in such a way:

foo.dig(*query)
4
max pleaner On

I would use Alex's answer for a typical use-case but since it splats out the array into arguments, there is more overhead and with large inputs, I get a stack too deep error. This isn't an error you will face unless you have a huge list but maybe worth understanding anyway.

# one million keys
# note that none of these are actually present in the hash
query = 1.upto(1_000_000).to_a

foo.dig(*query)
# => StackTooDeep

query.reduce(foo) do |memo, key|
  memo&.dig(key) || break
end
# => returns nil instantly