簡體   English   中英

在哈希中轉換哈希數組

[英]Convert array of hash in hash

實際上我有一個哈希數組:

[{:id=>"6", :created_at=>"2022-06-10", :value=>"2.159", :type=>"book"},
 {:id=>"8", :created_at=>"2022-06-10", :value=>"2.097", :type=>"poem"},
 {:id=>"3", :created_at=>"2022-06-10", :value=>"2.207", :type=>"book"}]

我想要類似的東西:

{
 {:id=>"6", :created_at=>"2022-06-10", :value=>"2.159", :type=>"book"},
 {:id=>"8", :created_at=>"2022-06-10", :value=>"2.097", :type=>"poem"},
 {:id=>"3", :created_at=>"2022-06-10", :value=>"2.207", :type=>"book"}
}

我該怎么做才能轉換它?

盡管您發布的第二個代碼塊無效(因為哈希需要綁定到其他標識符或對象),但您可能會猜測您想以某種方式將數組的對象(哈希)重新組合為其他方式.

如果是這樣,您可以使用以下方式將它們提取到變量中:

array_of_hashes = [{:id=>"6", :created_at=>"2022-06-10", :value=>"2.159", :type=>"book"},
 {:id=>"8", :created_at=>"2022-06-10", :value=>"2.097", :type=>"poem"},
 {:id=>"3", :created_at=>"2022-06-10", :value=>"2.207", :type=>"book"}]

hash_1, hash_2, hash_3 = array_of_hashes

另一種可能性是您想讓這些散列成為另一個散列的值:

array_of_hashes = [{:id=>"6", :created_at=>"2022-06-10", :value=>"2.159", :type=>"book"},
 {:id=>"8", :created_at=>"2022-06-10", :value=>"2.097", :type=>"poem"},
 {:id=>"3", :created_at=>"2022-06-10", :value=>"2.207", :type=>"book"}]

hash_of_hashes = array_of_hashes.each_with_object({}) do |hash, new_hash|
  id = hash[:id] # or some other calculated new key
  new_hash[id] = hash
end

這將產生一個像這樣的哈希:

{ 
  "6" => {:id=>"6", :created_at=>"2022-06-10", :value=>"2.159", :type=>"book"},
  "8" => {:id=>"8", :created_at=>"2022-06-10", :value=>"2.097", :type=>"poem"},
  "3" => {:id=>"3", :created_at=>"2022-06-10", :value=>"2.207", :type=>"book"}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM