如何在Ruby中合并多个哈希?

时间:2013-10-23 17:31:11

标签: ruby hash

h  = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }

Hash#merge适用于2个哈希:h.merge(h2)

如何合并3个哈希?

h.merge(h2).merge(h3)有效但有更好的方法吗?

10 个答案:

答案 0 :(得分:44)

你可以这样做:

h, h2, h3  = { a: 1 }, { b: 2 }, { c: 3 }
a  = [h, h2, h3]

p Hash[*a.map(&:to_a).flatten] #= > {:a=>1, :b=>2, :c=>3}

编辑:如果您有许多哈希值,这可能是正确的方法:

a.inject{|tot, new| tot.merge(new)}
# or just
a.inject(&:merge)

答案 1 :(得分:18)

由于 Ruby 2.0 ,可以更加慷慨地完成:

h.merge **h1, **h2

如果密钥重叠 - 后者当然优先:

h  = {}
h1 = { a: 1, b: 2 }
h2 = { a: 0, c: 3 }

h.merge **h1, **h2
# => {:a=>0, :b=>2, :c=>3}

h.merge **h2, **h1
# => {:a=>1, :c=>3, :b=>2}

答案 2 :(得分:10)

你可以做到

[*h,*h2,*h3].to_h
# => {:a=>1, :b=>2, :c=>3}

无论密钥是Symbol s还是

,这都有效

答案 3 :(得分:4)

class Hash  
  def multi_merge(*args)
    args.unshift(self)
    args.inject { |accum, ele| accum.merge(ele) }
  end
end

应该这样做。正如我所示,你可以很容易地将其打造成Hash。

答案 4 :(得分:3)

newHash = [h, h2, h3].each_with_object({}) { |oh, nh| nh.merge!(oh)}
# => {:a=>1, :b=>2, :c=>3}

答案 5 :(得分:3)

以下是我们在app中使用的2个monkeypatched :: Hash实例方法。以Minitest规格为后盾。出于性能原因,他们在内部使用merge!而不是merge

class ::Hash

  # Merges multiple Hashes together. Similar to JS Object.assign.
  #   Returns merged hash without modifying the receiver.
  #
  # @param *other_hashes [Hash]
  #
  # @return [Hash]
  def merge_multiple(*other_hashes)
    other_hashes.each_with_object(self.dup) do |other_hash, new_hash|
      new_hash.merge!(other_hash)
    end
  end

  # Merges multiple Hashes together. Similar to JS Object.assign.
  #   Modifies the receiving hash.
  #   Returns self.
  #
  # @param *other_hashes [Hash]
  #
  # @return [Hash]
  def merge_multiple!(*other_hashes)
    other_hashes.each(&method(:merge!))

    self
  end

end

测试:

describe "#merge_multiple and #merge_multiple!" do
  let(:hash1) {{
    :a => "a",
    :b => "b"
  }}
  let(:hash2) {{
    :b => "y",
    :c => "c"
  }}
  let(:hash3) {{
    :d => "d"
  }}
  let(:merged) {{
    :a => "a",
    :b => "y",
    :c => "c",
    :d => "d"
  }}

  describe "#merge_multiple" do
    subject { hash1.merge_multiple(hash2, hash3) }

    it "should merge three hashes properly" do
      assert_equal(merged, subject)
    end

    it "shouldn't modify the receiver" do
      refute_changes(->{ hash1 }) do
        subject
      end
    end
  end

  describe "#merge_multiple!" do
    subject { hash1.merge_multiple!(hash2, hash3) }

    it "should merge three hashes properly" do
      assert_equal(merged, subject)
    end

    it "shouldn't modify the receiver" do
      assert_changes(->{ hash1 }, :to => merged) do
        subject
      end
    end
  end
end

答案 6 :(得分:3)

Ruby 2.6允许merge接受多个参数:

h  = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }

h.merge(h2, h3) # => { a: 1, b: 2, c: 3 }

这也适用于Hash.merge!Hash.updatehere的文档。

简单得多:)

答案 7 :(得分:2)

使用reduce(与inject相同)

进行回答
hash_arr = [{foo: "bar"}, {foo2: "bar2"}, {foo2: "bar2b", foo3: "bar3"}]

hash_arr.reduce { |acc, h| (acc || {}).merge h }
# => {:foo2=>"bar2", :foo3=>"bar3", :foo=>"bar"}

解释

对于那些从Ruby或函数式编程开始的人,我希望这个简短的解释可能有助于理解这里发生的事情。

在Array对象(reduce)上调用时,hash_arr方法将迭代遍历数组的每个元素,并将块的返回值存储在累加器(acc)中。实际上,我的块的h参数将采用数组中每个哈希的值,acc参数将采用块通过每次迭代返回的值。

我们使用(acc || {})来处理acc为零的初始条件。请注意,merge方法优先考虑原始哈希中的键/值。这就是为什么"bar2b"的值不会出现在我的最终哈希值中的原因。

希望有所帮助!

答案 8 :(得分:2)

要建立@Oleg Afanasyev的答案,你也可以做到这一点:

h  = { a: 1 }
h2 = { b: 2 }
h3 = { c: 3 }

z = { **h, **h2, **h3 }  # => {:a=>1, :b=>2, :c=>3}

干杯!

答案 9 :(得分:1)

只是为了好玩,你也可以这样做:

a = { a: 1 }, { b: 2 }, { c: 3 }
{}.tap { |h| a.each &h.method( :update ) }
#=> {:a=>1, :b=>2, :c=>3}