Ruby在哈希中组合元素

时间:2012-01-24 21:17:38

标签: ruby join hash element

我有一个看起来像这样的:

data = {abc -> [[date1, val1], [date2,val2]], def -> [[date1,val3], [date2,val4]]}

我想加入abc和def元素,所以就像这样:

data = {join -> [[date1, val1+val3], [date2, val2+val4]] }

我该如何解决这个问题。请注意,哈希中还有其他元素不应修改。

1 个答案:

答案 0 :(得分:1)

我假设abcdefjoin实际上是符号。

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"