簡體   English   中英

紅寶石嵌套數組中哈希鍵的總和

[英]Sum of hash keys in nested array in ruby

我有一個包含具有相同鍵集的哈希數組的數組。 我需要對每個數組的每個鍵集求和,只剩下一個哈希數組。

array = [
  [{"x"=>"Apr, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10},
   {"x"=>"May, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10},
   {"x"=>"Jun, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10} ],
  [{"x"=>"Apr, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10},
   {"x"=>"May, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10},
   {"x"=>"Jun, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10} ],
  [{"x"=>"Apr, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10},
   {"x"=>"May, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10},
   {"x"=>"Jun, 2014", "price_rate"=>10, "cost_rate"=>10, "profit"=>10} ]
]

那會留給我

[{"x"=>"Apr, 2014", "price_rate"=>30, "cost_rate"=>30, "profit"=>30},
 {"x"=>"May, 2014", "price_rate"=>30, "cost_rate"=>30, "profit"=>30},
 {"x"=>"Jun, 2014", "price_rate"=>30, "cost_rate"=>30, "profit"=>30} ]

我嘗試將它們展平為單個數組,合並(這似乎從未給我帶來我期望的結果),並減少添加-但我無濟於事。

有一種簡潔的方法嗎?

編輯還要注意的是,每個數組中的哈希數可以變化。 該示例使用了一年的四分之一,但是生成的解決方案應該是不可知的,以允許輸入或輸入的數據集與數據集一樣少。

這是一種(純Ruby)方式,它使用Hash#update (也稱為merge! )形式,該形式使用一個塊來確定要合並的兩個哈希中存在的鍵的值:

array.flatten.each_with_object({}) { |g,h|
  h.update(g["x"]=>g.dup) { |_,oh,nh|
    oh.update(nh) { |k,ov,nv| (k=="x") ? ov : ov+nv } } }.values
  #=> [{"x"=>"Apr, 2014", "price_rate"=>30, "cost_rate"=>30, "profit"=>30},
  #    {"x"=>"May, 2014", "price_rate"=>30, "cost_rate"=>30, "profit"=>30},
  #    {"x"=>"Jun, 2014", "price_rate"=>30, "cost_rate"=>30, "profit"=>30}]

trh指出我原來的解決方案修改了我錯過的array 為了避免這種情況,我將g["x"]=>g更改為g["x"]=>g.dup

探究以遞歸方式使用deep_merge。 為此,您可以使用2個散列:

hash1.deep_merge(hash2) { |key, first, last| key == 'x' ? first : first + last }

這是在合並每個鍵值,除了第一列(應始終匹配)。 如果遍歷所有數組,則應該可以使用類似的策略將它們合並為一個數組。

更多信息: http : //api.rubyonrails.org/classes/Hash.html#method-i-deep_merge

暫無
暫無

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

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