繁体   English   中英

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

[英]Rails mapping array of hashes onto single hash

我有一系列的哈希像这样:

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

而我正在尝试将此映射到单个哈希,如下所示:

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

我已经实现了它

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

但我想知道是否有可能以更惯用的方式做到这一点(最好不使用局部变量)。

我怎样才能做到这一点?

您可以编写Enumerable#reduceHash#merge来完成您想要的任务。

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

减少数组类似于在每个元素之间粘贴方法调用。

例如[1, 2, 3].reduce(0, :+)就像说0 + 1 + 2 + 3并给出6

在我们的例子中,我们做了类似的事情,但使用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}

怎么样:

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

使用#inject

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

在这里,您可以使用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