first_response = [
{"xId" => "123", "yId" => "321"},
{"xId" => "x", "yId" => "y" }
]
first_response.each do |resp|
x_id = resp['xId']
y_id = resp['yId']
puts x_id.to_s
puts y_id.to_s
end
這給了我輸出
123
321
x
y
我要創建的輸出哈希是
{123=>{321}, x=>{y}}
第一個服務:我有一個哈希陣列,它有兩個不同的 ID 示例:(x_id 和 y_id)(回應中會有多個這樣的對)
我想創建一個散列,它應該包含我們從第一個服務中獲得的 x_id 和 y_ids 的匹配對,其中 x_id 作為所有對的鍵。
uj5u.com熱心網友回復:
如果您知道其中的每個散列first_response將恰好包含兩個鍵/值對,您可以提取它們的值,然后將該結果轉換為散列(請參閱 參考資料Enumerable#to_h):
first_response.to_h(&:values)
# {"123"=>"321", "x"=>"y"}
uj5u.com熱心網友回復:
看起來這種方法有效,但我不完全確定這是否正確
first_response = [{"xId"=>"123","yId"=> "321"}, {"xId"=>"x","yId"=> "y"}]
h = {}.tap do |element|
first_response.each do |resp|
x_id = resp['xId']
y_id = resp['yId']
element[x_id] = y_id
end
end
puts h.to_s
# {"123"=>"321", "x"=>"y"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/374984.html
