要散列的散列数组 [英] Array of hashes to hash
本文介绍了要散列的散列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有单个哈希数组
For example, I have array of single hashes
a = [{a: :b}, {c: :d}]
将它转换成这个的最好方法是什么?
What is best way to convert it into this?
{a: :b, c: :d}
推荐答案
您可以使用
a.reduce Hash.new, :merge
直接产生
{:a=>:b, :c=>:d}
请注意,如果发生冲突,顺序很重要.后面的散列覆盖以前的映射,参见例如:
Note that in case of collisions the order is important. Latter hashes override previous mappings, see e.g.:
[{a: :b}, {c: :d}, {e: :f, a: :g}].reduce Hash.new, :merge # {:a=>:g, :c=>:d, :e=>:f}
这篇关于要散列的散列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文