哈希散列数组 [英] Array of hashes to hash

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

问题描述

例如,我有一些单哈希值

  a = [{a::b},{c:: d}] 

将其转换为此值的最佳方法是什么?

  {a::b,c::d} 


<您可以使用

  a.reduce Hash.new, :合并

直接产生

  {:a =>:b,:c =>:d} 

请注意,如果发生碰撞,顺序很重要。后者哈希会覆盖以前的映射,参见例如:

  [{a::b},{c::d},{e ::f:a::g}]。reduce Hash.new,:merge#{:a =>:g,:c =>:d,:e =>:f} 


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}

解决方案

You may use

a.reduce Hash.new, :merge

which directly yields

{: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屋!

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