2014-02-05 67 views
-1

我想合併兩個哈希數組的嵌套數組。如何在Ruby中深度合併兩個嵌套的數組哈希?

h1 = {:f => [{:f => [{:name => "a","type"=>"t",:mode=>"n"},{:name => "b","type"=>"t",:mode=>"n"}], :name => "p",:t=>"r"}]} 

h2 = {:f => [{:f => [{:name => "a","type"=>"t",:mode=>"n"},{:name => "c","type"=>"t",:mode=>"n"}], :name => "p",:t=>"r"}]} 

這是我期待的輸出。

{:f => [{:f => [{:name => "a","type"=>"t",:mode=>"n"},{:name => "b","type"=>"t",:mode=>"n"},{:name => "c","type"=>"t",:mode=>"n"}], :name => "p",:t=>"r"}]} 

我已使用deep_merge & deep_merge!但是,這並沒有給我想要的結果。欣賞任何指針。

感謝, 那伏乃爾

+0

'deep_merge'?從來沒有聽說過。啊,來自Rails。您應該添加一個'Rails'或'ActiveSupport'標籤,並在您的句子中引用「我已經使用deep_merge ...」。 (Downvote不是我的) –

+0

有沒有簡單的方法來做到這一點,因爲你想對待你的外部數組不同於內部 - 你想迭代前者和後者。沒有任何通用解決方案適用於任何嵌套結構。 – BroiSatse

回答

0

正如評論指出會有你想要的東西沒有通用的解決方案。下面的代碼應爲您的嵌套結構工作(並且是極其醜陋):

{f: [h1[:f].first.deep_merge(h2[:f].first) { |key, old, new| old == new ? new : (Array.wrap(old) + Array.wrap(new)).uniq }]} 

的問題是 - 你爲什麼要這麼做?最有可能的是有更好的方式來做你正在努力達到的目標。

0

這是我寫的,解決它:

class ::Array 
    def mergeFields(second) 
     second.each do |sElem| 
     match = false 
     self.each do |fElem| 
     puts "Comparing: #{sElem[:name]} and #{fElem[:name]}" 
     if sElem[:name] == fElem[:name] 
     if !sElem[:fields].nil? && !fElem[:fields].nil? && sElem[:fields].is_a?(Array) && fElem[:fields].is_a?(Array) 
      fElem[:fields].mergeFields(sElem[:fields]) 
     end 
     match = true 
     break 
     end 
     end 
     if match == false 
     self << sElem 
     end 
     end 
    end 
    end 

    h1 = {:fields => [{:fields => [{:name => "a","type"=>"t",:mode=>"n"},{:name => "b","type"=>"t",:mode=>"n"}], :name => "p",:t=>"r"},{:name => "e", :t => "s", :m => "n"}]} 


    h2 = {:fields => [{:fields => [{:name => "a","type"=>"t",:mode=>"n"},{:name => "c","type"=>"t",:mode=>"n"}], :name => "p",:t=>"r"},{:name => "q", :t => "s", :m => "n"}]} 

    h1[:fields].mergeFields(h2[:fields])