在 Ruby 中合并多维哈希 [英] Merging multi-dimensional hashes in Ruby

查看:44
本文介绍了在 Ruby 中合并多维哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个散列,它们的结构与此类似:

I have two hashes which have a structure something similar to this:

hash_a = { :a => { :b => { :c => "d" } } }
hash_b = { :a => { :b => { :x => "y" } } }

我想将这些合并在一起以产生以下哈希:

I want to merge these together to produce the following hash:

{ :a => { :b => { :c => "d", :x => "y" } } }

合并函数将第一个散列中的 :a 值替换为第二个散列中 :a 的值.所以,我写了自己的递归合并函数,如下所示:

The merge function will replace the value of :a in the first hash with the value of :a in the second hash. So, I wrote my own recursive merge function, which looks like this:

def recursive_merge( merge_from, merge_to )
    merged_hash = merge_to
    first_key = merge_from.keys[0]
    if merge_to.has_key?(first_key)
        merged_hash[first_key] = recursive_merge( merge_from[first_key], merge_to[first_key] )
    else
        merged_hash[first_key] = merge_from[first_key]
    end
    merged_hash
end

但我收到一个运行时错误:无法在迭代过程中将新键添加到哈希中.在 Ruby 中合并这些哈希的最佳方法是什么?

But I get a runtime error: can't add a new key into hash during iteration. What's the best way of going about merging these hashes in Ruby?

推荐答案

如果把recursive_merge的第一行改成

If you change the first line of recursive_merge to

merged_hash = merge_to.clone

它按预期工作:

recursive_merge(hash_a, hash_b)    
->    {:a=>{:b=>{:c=>"d", :x=>"y"}}}

在移动过程中更改哈希很麻烦,您需要一个工作区"来累积结果.

Changing the hash as you move through it is troublesome, you need a "work area" to accumulate your results.

这篇关于在 Ruby 中合并多维哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆