Merging multi-dimensional hashes in Ruby

前端 未结 6 2133
轮回少年
轮回少年 2020-12-07 02:38

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

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


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 02:56

    You can do it in one line :

    merged_hash = hash_a.merge(hash_b){|k,hha,hhb| hha.merge(hhb){|l,hhha,hhhb| hhha.merge(hhhb)}}
    

    If you want to imediatly merge the result into hash_a, just replace the method merge by the method merge!

    If you are using rails 3 or rails 4 framework, it is even easier :

    merged_hash = hash_a.deep_merge(hash_b)
    

    or

    hash_a.deep_merge!(hash_b)
    

提交回复
热议问题