給定一個源哈希陣列:
[{:country=>'england', :cost=>12.34}, {:country=>'scotland', :cost=>56.78}]
是否有一個簡潔的 Ruby 單行器將其轉換為單個散列,其中:country原始散列中的鍵值(保證是唯一的)成為新散列中的鍵?
{:england=>12.34, :scotland=>56.78}
uj5u.com熱心網友回復:
這應該做你想做的
countries.each_with_object({}) { |country, h| h[country[:country].to_sym] = country[:cost] }
=> {:england=>12.34, :scotland=>56.78}
uj5u.com熱心網友回復:
您可以使用Enumerable#inject做到這一點:
countries.inject({}) { |hsh, element| hsh.merge!(element[:country].to_sym => element[:cost]) }
=> {:england=>12.34, :scotland=>56.78}
我們將累加器初始化為{},然后遍歷初始陣列的每個元素,并將新的格式化元素添加到累加器中。
要補充的一點是,使用hsh.mergeorhsh.merge!將對輸出產生相同的效果,因為inject它將累加器設定hsh為塊的回傳值。但是,merge!在記憶體使用方面,使用更好,因為它merge總是會生成一個新的哈希,而merge!將合并應用到相同的現有哈希上。
uj5u.com熱心網友回復:
另一種可能的解決方案是:
countries.map(&:values).to_h
=> {"england"=>12.34, "scotland"=>56.78}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/455214.html
標籤:红宝石
