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.): PrintKey -> "键名":andValue-> "值",
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
casestatements: More readable than a mess ofif/elsifchecks—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
相关产品推荐
相关产品推荐

