Ruby:如何知道其“路径”如何检索哈希值?

问题描述 投票:0回答:1

我有这个哈希

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

而且我知道我想要的值的'路径':

path = ['titles','secondary']

我如何检索对应的值,即Matt Monro

此作品

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

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

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

不显示任何内容。

我是红宝石新手,为什么这不起作用?

谢谢

ruby hash traversal
1个回答
0
投票

[Hash.dig接受可变数量的参数,要将数组转换为“可变参数”,您需要使用*splat operator

parentNode.dig(*path)
© www.soinside.com 2019 - 2024. All rights reserved.