Ruby中如何遍历大型嵌套Hash提取所有小时段的datetime值
datetime Values from a Nested Ruby Hash Hey there! Let's ditch that manual index-tweaking hassle—Ruby's built-in tools make this way simpler than you think. Here's how to do it, step by step, tailored for folks new to Ruby:
Basic Loop Approach (Easy to Follow)
This straightforward method lets you see exactly what's happening at each nested level, perfect for learning:
# Assume your hash is stored in this variable weather_data = { "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"}, # ... rest of the hours ] } ] } # Loop through each day (works even if you add more days later!) weather_data['days'].each do |day| # Then loop through every hour in the current day's hours array day['hours'].each do |hour| # Print the datetime value for this hour puts hour['datetime'] end end
How this works:
weather_data['days'].eachiterates over every entry in thedaysarray (right now you have one, but this code handles multiple days automatically).- Inside that loop,
day['hours'].eachgoes through every hour object in the current day'shourslist. hour['datetime']pulls the exact value you need from each hour's hash.
Concise Approach (Collect Values into an Array)
If you want to store all datetime values in a reusable array (instead of just printing them), use flat_map to cleanly flatten nested results into a single list:
# Gather all hourly datetimes into one array all_hourly_datetimes = weather_data['days'].flat_map do |day| day['hours'].map { |hour| hour['datetime'] } end # Use the array however you need puts all_hourly_datetimes # Or loop through it later: all_hourly_datetimes.each { |datetime| puts datetime }
Why flat_map?
Without flat_map, you'd end up with a 2D array (one array per day of hour datetimes). flat_map combines those nested arrays into one simple list—ideal for most use cases.
Robust Version (Handle Missing Data)
If you're working with API responses that might have missing hours arrays or datetime keys, add quick checks to avoid crashes:
weather_data['days'].each do |day| # Skip this day if there's no valid hours array next unless day['hours'].is_a?(Array) day['hours'].each do |hour| # Only print if the datetime key exists puts hour['datetime'] if hour.key?('datetime') end end
This ensures your code stays stable even if the input data isn't perfect.
内容的提问来源于stack exchange,提问作者CodrinM

