简体   繁体   English

Ruby,访问哈希中的嵌套值

[英]Ruby, accessing a nested value in a hash

I have the following hash. 我有以下哈希。 Using ruby, I want to get the value of "runs". 使用红宝石,我想获得“游程”的价值。 I can't figure out how to do it. 我不知道该怎么做。 If I do my_hash['entries'] , I can dig down that far. 如果我执行my_hash['entries'] ,则可以深入研究。 If I take that value and dig down lower, I get this error: no implicit conversion of String into Integer: 如果我采用该值并往下钻,则会出现以下错误: no implicit conversion of String into Integer:

{"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588, ...

Assuming that you want to lookup values by id , Array#detect comes to the rescue: 假设您要通过id查找值, Array#detect可以解决:

h = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]}]}
#           ⇓⇓⇓⇓⇓⇓⇓ lookup element with id = 7 
h['entries'].detect { |e| e['id'] == 7 }['runs']
            .detect { |e| e['id'] == 2588 }
#⇒ { "id" => 2588 }

As you have an array inside the entries so you can access it using an index like this: 由于entries有一个数组,因此可以使用像这样的索引来访问它:

my_hash["entries"][0]["runs"]

You need to follow the same for accessing values inside the runs as it is also an array. 您也需要遵循相同的操作来访问runs值,因为它也是一个数组。

Hope this helps. 希望这可以帮助。

I'm not sure about your hash, as it's incomplete. 我不确定您的哈希,因为它不完整。 So , guessing you have multiple run values like: 因此,假设您有多个运行值,例如:

hash = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]},
                                {"id"=>"8", "runs"=>[{"id"=>2589}]},
                                {"id"=>"9", "runs"=>[{"id"=>2590}]}]}

Then, you can do 那你就可以

hash["entries"].map{|entry| entry["runs"]}

OUTPUT 输出值

[[{"id"=>2588}], [{"id"=>2589}], [{"id"=>2590}]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM