Ruby combine elements in hash

*爱你&永不变心* 提交于 2019-12-25 08:59:37

问题


I have a has that looks like this:

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

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.


回答1:


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"


来源:https://stackoverflow.com/questions/8994297/ruby-combine-elements-in-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!