我有一个散列,里面有很多散列,值可能是一个数组,这个数组由许多散列组成,我想打印所有键值对,如果值是数组,那么它必须打印
"pageOfResults": "Array" # I don't want actual array here, I want the string "Array" to be printed.
Run Code Online (Sandbox Code Playgroud)
Of 如果hash跟在后面,那么就需要打印
"PolicyPayment": "Hash"
Run Code Online (Sandbox Code Playgroud)
否则它需要打印键和值
Key -> "CurrencyCode":
Value-> "SGD",
Run Code Online (Sandbox Code Playgroud)
哈希跟随
a={
"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",
},
],
},
}
]
}
Run Code Online (Sandbox Code Playgroud)
我编写的程序来打印这些值
a.each do |key,value|
puts "key->" + key.to_s
if value.is_a?Array
value.each do |v|
v.each do |key,value|
puts "key->"+key.to_s
puts "value->"+value.to_s
end
end
else
puts "value->"+value.to_s
end
Run Code Online (Sandbox Code Playgroud)
该程序首先打印哈希级别及其值,我也可以进行递归调用以打印所有值,
但我的问题是,有没有什么办法可以编写 Ruby 风格的代码来轻松实现这一点?或者有什么更好的方法?
简单的?方法可以解决问题:
printer = ->(enum) do
enum.each do |k, v|
enum = [k, v].detect(&Enumerable.method(:===))
if enum.nil?
puts("Key -> #{k}\nValue -> #{v}")
else
puts ("#{k} -> 'Array'") if v.is_a?(Array)
printer.(enum)
end
end
end
printer.(a)
Run Code Online (Sandbox Code Playgroud)
生产:
PageOfResults -> 'Array'
Key -> CurrencyCode
Value -> SGD
Key -> IpAddress
Value ->
Key -> InsuranceApplicationId
Value -> 6314
Key -> PolicyNumber
Value -> SL10032268
Key -> PolicyPaymentId
Value -> 2188
Key -> PaymentMethod
Value -> GIRO
Key -> InsuranceProductDiscountDetail
Value ->
Results -> 'Array'
Key -> Id
Value -> 8113
Key -> InsuranceProductId
Value -> 382
Key -> ApplicationProductSelectedId
Value -> 62043
Key -> InsuranceProductId
Value -> 382
Key -> ProductCode
Value -> TL70-90
Run Code Online (Sandbox Code Playgroud)