简体   繁体   中英

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. If I take that value and dig down lower, I get this error: 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:

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:

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

You need to follow the same for accessing values inside the runs as it is also an array.

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}]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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