Search code examples
rubyhashtraversal

Ruby: how can I retrieve a value in a hash knowing its (array) path?


I've got this hash

parentNode = {
  "titles" => { 
    "primary" => "On Days Like These",
    "secondary" => "Matt Monro",
    "tertiary" => nil
  },
  "synopses" => nil,
  "image_url" => "https://ichef.bbci.co.uk/images/ic/{recipe}/p01bqrb8.jpg",
  "duration" => nil
}

and I know the 'path' of the value I want :

path = ['titles','secondary']

How can I retrieve the corresponding value, which is Matt Monro ?

This works

puts parentNode['titles']['secondary']

but what I want is to fetch that same data using the path variable defined above. But

  puts parentNode[path]
  puts parentNode.dig(path)

does not shows anything.

I'm new to ruby, why is this not working ?

Thanks


Solution

  • Hash.dig accepts variable number of arguments, to convert array into "variable arguments" you need to use * (splat operator)

    parentNode.dig(*path)