'i have a large hash and i want to get specific values in ruby

So i have this large Hash :

> {"queryCost"=>1,
 "latitude"=>43.1232321,
 "longitude"=>59.3123213,
 "resolvedAddress"=>"43.1232321,59.3123213",
 "address"=>"43.1232321,59.3123213",
 "timezone"=>"Asia/Samarkand",
 "tzoffset"=>5.0,
 "days"=>[{"datetime"=>"2022-03-30",
  "datetimeEpoch"=>1648580400,
  "source"=>"obs"},
  "hours"=>
   [{"datetime"=>"00:00:00",
     "datetimeEpoch"=>1648580400,
     "source"=>"obs"},
    {"datetime"=>"01:00:00",
     "datetimeEpoch"=>1648584000,
     "source"=>"obs"},
    {"datetime"=>"02:00:00",
     "datetimeEpoch"=>1648587600,
     "source"=>"obs"},
    {"datetime"=>"03:00:00",
     "datetimeEpoch"=>1648591200,
     "source"=>"obs"},
    {"datetime"=>"04:00:00",
     "datetimeEpoch"=>1648594800,
     "source"=>"obs"},
    {"datetime"=>"05:00:00",
     "datetimeEpoch"=>1648598400,
     "source"=>"obs"},
    {"datetime"=>"06:00:00",
     "datetimeEpoch"=>1648602000,
     "source"=>"obs"}]},
   

What i want is to get all hours that are 24, i can get them manually 1 by 1, using this hash_json['days'][0]['hours'][0]['datetime] and so on chaning 0 to 24, but how can i do a loop that gets me something like this :

loop through hash

puts hash hours datatime

end

output: "00:00:00" "01:00:00" ... until it gets "24:00:00" that is the last one.

I did see some examples but they where to simple, to use them on this hash, and since im new to ruby i cant rearly get it.



Solution 1:[1]

You are trying to do too much all at once with hash_json['days'][0]['hours'][0]['datetime]. I suggest breaking this into smaller pieces. For example do days = hash_json['days']. Now you have a variable with simpler structure. In this case it is a list. You can get the first element with days[0] or loop over the list with days.each or days.map. I suggest you read about each and map to learn what they are good for and how they work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Code-Apprentice