arraysrubyhashsplat

Ruby hash.dig using array as argument?


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


Solution

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

    foo.dig(*query)