Ruby在哈希中组合元素 [英] Ruby combine elements in hash
本文介绍了Ruby在哈希中组合元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的食物:
I have a has that looks like this:
data = {abc -> [[date1, val1], [date2,val2]], def -> [[date1,val3], [date2,val4]]}
我想加入abc和def元素,就像这样:
I want to join the abc and def elements so it's like this:
data = {join -> [[date1, val1+val3], [date2, val2+val4]] }
我该如何处理.请注意,哈希中还有其他不应修改的元素.
How do I go about this. Note that there are other elements in the hash that should not be modified.
推荐答案
我假设abc
,def
和join
实际上是符号.
I am assuming that abc
, def
, and join
are actually Symbols.
a = Hash[data.delete(:abc)] # extract data[:abc] and convert it to a Hash ("a")
b = Hash[data.delete(:def)] # extract data[:def] and convert it to a Hash ("b")
data[:join] = a.map do |k,v| # iterate over one of the extracted Hashes
[k, v + (b[k] || 0)] # for each key, return a 2-item array with the key,
end # and the sum of the values from "a" and "b"
这篇关于Ruby在哈希中组合元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文