简体   繁体   English

Rails将哈希数组映射到单个哈希

[英]Rails mapping array of hashes onto single hash

I have an array of hashes like so: 我有一系列的哈希像这样:

 [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]

And I'm trying to map this onto single hash like this: 而我正在尝试将此映射到单个哈希,如下所示:

{"testPARAM2"=>"testVAL2", "testPARAM1"=>"testVAL1"}

I have achieved it using 我已经实现了它

  par={}
  mitem["params"].each { |h| h.each {|k,v| par[k]=v} } 

But I was wondering if it's possible to do this in a more idiomatic way (preferably without using a local variable). 但我想知道是否有可能以更惯用的方式做到这一点(最好不使用局部变量)。

How can I do this? 我怎样才能做到这一点?

You could compose Enumerable#reduce and Hash#merge to accomplish what you want. 您可以编写Enumerable#reduceHash#merge来完成您想要的任务。

input = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
input.reduce({}, :merge)
  is {"testPARAM2"=>"testVAL2", "testPARAM1"=>"testVAL1"}

Reducing an array sort of like sticking a method call between each element of it. 减少数组类似于在每个元素之间粘贴方法调用。

For example [1, 2, 3].reduce(0, :+) is like saying 0 + 1 + 2 + 3 and gives 6 . 例如[1, 2, 3].reduce(0, :+)就像说0 + 1 + 2 + 3并给出6

In our case we do something similar, but with the merge function, which merges two hashes. 在我们的例子中,我们做了类似的事情,但使用merge函数,它合并了两个哈希。

[{:a => 1}, {:b => 2}, {:c => 3}].reduce({}, :merge)
  is {}.merge({:a => 1}.merge({:b => 2}.merge({:c => 3})))
  is {:a => 1, :b => 2, :c => 3}

How about: 怎么样:

h = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
r = h.inject(:merge)

Use #inject 使用#inject

hashes = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]
merged = hashes.inject({}) { |aggregate, hash| aggregate.merge hash }
merged # => {"testPARAM1"=>"testVAL1", "testPARAM2"=>"testVAL2"}

Here you can use either inject or reduce from Enumerable class as both of them are aliases of each other so there is no performance benefit to either. 在这里,您可以使用Enumerable类中的injectreduce ,因为它们都是彼此的别名,因此两者都没有性能优势。

 sample = [{"testPARAM1"=>"testVAL1"}, {"testPARAM2"=>"testVAL2"}]

 result1 = sample.reduce(:merge)
 # {"testPARAM1"=>"testVAL1", "testPARAM2"=>"testVAL2"}

 result2 = sample.inject(:merge)
 # {"testPARAM1"=>"testVAL1", "testPARAM2"=>"testVAL2"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM