使用其他哈希构造哈希

时间:2011-04-15 20:53:03

标签: ruby ruby-on-rails-3 join hash

我想加入两个或更多这样的哈希。

h1 = { :es => { :hello  => "You" } }
h2 = { :es => { :bye => "Man" } } 

我怎么能得到这个?

h1 + h2 = { :es => { :hello => "you", :bye => "Man" } }

感谢。

4 个答案:

答案 0 :(得分:5)

irb(main):001:0> h1 = {:es => {:hello => "You"}}
=> {:es=>{:hello=>"You"}}
irb(main):002:0> h2 = {:es => {:bye => "Man"}}
=> {:es=>{:bye=>"Man"}}
irb(main):003:0> h1.each_key {|x| h1[x].merge! h2[x]}
=> {:es=>{:bye=>"Man", :hello=>"You"}}

答案 1 :(得分:4)

你想要的是deep_merge方法。完全符合你的要求。

ruby-1.9.2-p136 :001 > {:es => {:hello => "You" } }.deep_merge({:es => {:bye => "Man"}})
=> {:es=>{:hello=>"You", :bye=>"Man"}}

http://apidock.com/rails/ActiveSupport/CoreExtensions/Hash/DeepMerge/deep_merge

答案 2 :(得分:0)

与activesupport deep_merge类似,但采用功能性方法。以递归方式工作:

class Hash
  def inner_merge(other_hash)
    other_hash.inject(self) do |acc, (key, value)|
      if (acc_value = acc[key]) && acc_value.is_a?(Hash) && value.is_a?(Hash)
        acc.merge(key => acc_value.inner_merge(value))
      else
        acc.merge(key => value)
      end
    end       
  end
end

h1.inner_merge(h2) #=> {:es=>{:hello=>"You", :bye=>"Man"}}

答案 3 :(得分:0)

如果您不使用ActiveSupport,此Proc将执行深度合并。 1.8.7& 1.9.2兼容。

dm = lambda {|l,r| l.merge(r) {|k,ov,nv| l[k] = ov.is_a?(Hash) ? dm[ov, nv || {}] : nv} }
dm[h1,h2]
#  => {:es=>{:hello=>"You", :bye=>"Man"}}