我想從具有相同鍵和平均值的多個哈希數組中創建一個數組/散列。我的數組:從數組中添加哈希
[{:amount=>897500, :gross_amount=>897500, :tax=>147500, :hotel_fees=>0, :base_fare=>750000, :currency=>"INR"}, {:amount=>1006500, :gross_amount=>1006500, :tax=>156500, :hotel_fees=>0, :base_fare=>850000, :currency=>"INR"}]
現在我想回到這樣的事情:
{:amount=>952000, :gross_amount=>952000, :tax=>152000, :hotel_fees=>0, :base_fare=>800000, :currency=>"INR"}
其中值是值從同一個密鑰每個哈希的平均值。
有沒有簡單的方法來做到這一點。我嘗試過使用合併,但貨幣變爲0。
我嘗試:
p[0].merge(p[1]){|k,v1,v2| (v1+v2)/2 unless v1 && v2 == "INR"}
編輯:
其實我的問題並沒有到此結束,所以獲得平均後,我需要插入另一哈希內的值。 所以我用這樣的事情:
price_array = offer_values.map do |v|
v.inject do |k, v|
k.merge!(price: k[:price].merge(v[:price]){|_, a, b| [a, b].flatten })
end
end
price_array.map do |o|
o[:price] = {}.tap{ |h| o[:price].each {|k, list| h[k] = list.all?{|e| [Fixnum, NilClass].include? e.class} ? list.map(&:to_i).sum/list.size : list.compact.first ; h } }
end
哪裏offer_array是一個在單獨的哈希我的原單/第一個數組。這我已經嘗試過2和3次哈希,它正在工作。
如果你們有任何改善代碼的建議,它是開放的。
_ 「我嘗試過使用合併」 - 你能否顯示你的嘗試? – Stefan
合併返回這個'{:amount => 952000,:gross_amount => 952000,:tax => 152000,:hotel_fees => 0,:base_fare => 800000,:currency => nil}' – Ravi
我不能貨幣零。 – Ravi