在Ruby哈希中将相同键的值一起添加

时间:2022-10-10 12:19:32

I have a hash table that was created from a .txt file. Certain elements in the hash table has the same key. Ruby takes the last instance and uses that value in the hash table. How would I go about adding the values of duplicate keys together?

我有一个从.txt文件创建的哈希表。哈希表中的某些元素具有相同的键。 Ruby获取最后一个实例并在哈希表中使用该值。我如何将重复键的值添加到一起?

For example, if I have a hash table: hash = { a => 1, a => 2, b => 3 }

例如,如果我有一个哈希表:hash = {a => 1,a => 2,b => 3}

I would like the resulting hash table to be: hash = { a => 3, b => 3 }

我希望得到的哈希表是:hash = {a => 3,b => 3}

1 个解决方案

#1


3  

Use Block Form of Hash#Update

If you want to replace the values in your current hash by adding them together with the values associated with duplicate keys stored in another hash, you probably want to use the block form of Hash#update. The block defines what to do with duplicate keys; in this case, we simply add their values together. For example:

如果要通过将当前哈希中的值与将存储在另一个哈希中的重复键相关联的值一起添加来替换当前哈希中的值,则可能需要使用哈希#update的块形式。该块定义了如何处理重复键;在这种情况下,我们只需将它们的值相加。例如:

h1 = { a: 1, b: 3 }
h2 = { a: 2 }
h1.update(h2) { |k, v1, v2| v1 + v2 }
# => {:a=>3, :b=>3}

Note that this is an in-place change; you're actually modifying the values in h1. If you want to return a new hash with the merged values rather than overwriting h1, just use Hash#merge instead of Hash#update.

请注意,这是一个就地更改;你实际上是在修改h1中的值。如果要返回包含合并值而不是覆盖h1的新哈希,只需使用Hash #incin而不是Hash#update。

#1


3  

Use Block Form of Hash#Update

If you want to replace the values in your current hash by adding them together with the values associated with duplicate keys stored in another hash, you probably want to use the block form of Hash#update. The block defines what to do with duplicate keys; in this case, we simply add their values together. For example:

如果要通过将当前哈希中的值与将存储在另一个哈希中的重复键相关联的值一起添加来替换当前哈希中的值,则可能需要使用哈希#update的块形式。该块定义了如何处理重复键;在这种情况下,我们只需将它们的值相加。例如:

h1 = { a: 1, b: 3 }
h2 = { a: 2 }
h1.update(h2) { |k, v1, v2| v1 + v2 }
# => {:a=>3, :b=>3}

Note that this is an in-place change; you're actually modifying the values in h1. If you want to return a new hash with the merged values rather than overwriting h1, just use Hash#merge instead of Hash#update.

请注意,这是一个就地更改;你实际上是在修改h1中的值。如果要返回包含合并值而不是覆盖h1的新哈希,只需使用Hash #incin而不是Hash#update。