[英]Ruby creating a new hash from an array of key, value
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
This gives me outputs
123
321
x
y
output hash 我要創建的是 {123=>{321}, x=>{y}}`
`第一個服務:我有一個 hash 數組,它有兩個不同的 id 示例:(x_id 和 y_id)(在響應中會有多個這樣的對)
我想創建一個 hash,它應該包含我們從第一個服務中獲得的 x_id 和 y_id 的匹配對,其中 x_id 作為所有對的鍵。
看起來這種方法有效,但我不完全確定這是否正確
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"}
如果您知道 first_response 中的每個first_response
將恰好包含兩個鍵/值對,則可以提取它們的值,然后將結果轉換為 hash(請參閱Enumerable#to_h
):
first_response.to_h(&:values)
# {"123"=>"321", "x"=>"y"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.