Ruby 组合哈希中的元素

发布于 2024-12-28 13:14:32 字数 292 浏览 3 评论 0原文

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

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

我想加入 abc 和 def 元素,所以它是这样的:

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

我该如何去做。请注意,哈希中还有其他不应修改的元素。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮世清欢 2025-01-04 13:14:32

我假设 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"

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文