问题描述
我有一系列的散列,如下所示:
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"}
我已经使用
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).
我该怎么做?
推荐答案
您可以编写Enumerable#reduce
和Hash#merge
来完成所需的操作.
You could compose Enumerable#reduce
and Hash#merge
to accomplish what you want.
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.
例如[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}
这篇关于Rails将哈希数组映射到单个哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!