You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中如何遍历大型嵌套Hash提取所有小时段的datetime值

Extracting All Hourly 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'].each iterates over every entry in the days array (right now you have one, but this code handles multiple days automatically).
  • Inside that loop, day['hours'].each goes through every hour object in the current day's hours list.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:04:03