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

Ruby如何优雅实现嵌套Hash的键值对规则化打印?

Ruby-idiomatic Way to Traverse Nested Hashes with Arrays

Hey there! Let's fix that nested hash traversal to handle any depth of nested structures, while sticking to your required output rules. Recursion is the perfect fit here—it's clean, readable, and totally Ruby-style.

First, let's recap your requirements to make sure we're on the same page:

  • When the value is an Array: Print "键名": "Array" (no need to show the array's contents)
  • When the value is a Hash: Print "键名": "Hash" then traverse into this hash
  • For all other value types (strings, numbers, nil, etc.): Print Key -> "键名": and Value-> "值",

Here's a concise, recursive solution that meets all your needs:

def print_nested_structure(data)
  # Handle hashes first—this is our main traversal point
  if data.is_a?(Hash)
    data.each do |key, value|
      case value
      when Array
        puts "\"#{key}\": \"Array\""
        # Optional: If you ever need to traverse hash elements inside the array, uncomment below
        # value.each { |item| print_nested_structure(item) if item.is_a?(Hash) }
      when Hash
        puts "\"#{key}\": \"Hash\""
        print_nested_structure(value)
      else
        puts "Key -> \"#{key}\":"
        puts "Value-> \"#{value}\","
      end
    end
  end
end

# Test it with your sample hash
sample_hash = {
  "PageOfResults": [
    {
      "CurrencyCode": "SGD",
      "IpAddress": nil,
      "InsuranceApplicationId": 6314,
      "PolicyNumber": "SL10032268",
      "PolicyPayment": {
        "PolicyPaymentId": 2188,
        "PaymentMethod": "GIRO"
      },
      "InsuranceProductDiscountDetail": nil,
      "ProductDetails": {
        "Results": [
          {
            "Id": 8113,
            "InsuranceProductId": 382,
            "ApplicationProductSelectedId": 62043
          },
          {
            "InsuranceProduct": {
              "InsuranceProductId": 382,
              "ProductCode": "TL70-90"
            }
          }
        ]
      }
    }
  ]
}

print_nested_structure(sample_hash)

Why this works better than your original code:

  • Recursion handles infinite depth: No matter how many layers of hashes or arrays-with-hashes you have, this method will traverse them all automatically. Your original code only went two layers deep, which breaks for more complex structures.
  • Ruby-style case statements: More readable than a mess of if/elsif checks—this makes the logic easy to follow at a glance.
  • Flexibility: I added an optional line to traverse hash elements inside arrays if you ever need that (just uncomment it). Right now it follows your rule of only printing "键名": "Array" for arrays.
  • Clean string interpolation: Using #{key} and #{value} is the Ruby way to build strings, instead of clunky + concatenation.

Sample Output (matching your rules):

"PageOfResults": "Array"
Key -> "CurrencyCode":
Value-> "SGD",
Key -> "IpAddress":
Value-> "",
Key -> "InsuranceApplicationId":
Value-> "6314",
Key -> "PolicyNumber":
Value-> "SL10032268",
"PolicyPayment": "Hash"
Key -> "PolicyPaymentId":
Value-> "2188",
Key -> "PaymentMethod":
Value-> "GIRO",
Key -> "InsuranceProductDiscountDetail":
Value-> "",
"ProductDetails": "Hash"
"Results": "Array"

内容的提问来源于stack exchange,提问作者Rajagopalan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:13:17