Ruby-on-rails Rails 将散列数组映射到单个散列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11856407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:49:35  来源:igfitidea点击:

Rails mapping array of hashes onto single hash

ruby-on-railsrubyarrayshash

提问by Bart Platak

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?

我怎样才能做到这一点?

回答by cjhveal

You could compose Enumerable#reduceand Hash#mergeto 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 + 3and 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.

在我们的例子中,我们做了一些类似的事情,但使用了合并函数,它合并了两个散列。

[{: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}

回答by shigeya

How about:

怎么样:

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

回答by Joshua Cheek

Use #inject

使用#inject

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

回答by Nikhil Mohadikar

Here you can use either injector reducefrom Enumerableclass as both of them are aliases of each other so there is no performance benefit to either.

在这里,您可以使用Enumerable类中的注入减少,因为它们都是彼此的别名,因此两者都没有性能优势。

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

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

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