Ruby:如何在知道其(数组)路径的散列中检索值?

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

我有这个哈希值

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
}

我知道我想要的值的 'path' :

path = ['titles','secondary']

如何检索相应的值,即 Matt Monro

这个有效

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

但我想要的是使用上面定义的 path 变量获取相同的数据。但是

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

不显示任何内容。

我是 ruby 的新手,为什么这不起作用?

谢谢

Hash.dig 接受可变数量的参数,要将数组转换为 "variable arguments" 你需要使用 * (splat operator)

parentNode.dig(*path)