Rails将哈希数组映射到单个哈希 [英] Rails mapping array of hashes onto single hash

查看:93
本文介绍了Rails将哈希数组映射到单个哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列的散列,如下所示:

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#reduceHash#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将哈希数组映射到单个哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆