加入键的数组的哈希与Excel等VLOOKUP键值对 [英] Joining an array of keys to a hash with key value pairs like excel vlookup

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

问题描述

我有钥匙的一个排序的数组是这样的:

I've got an unsorted array of keys like this:

keys = ["ccc", "ddd", "ggg", "aaa", "bbb"]

和散列

hash = {"ddd" => 4, "aaa" => 1, "bbb" => 2, "eee" => 5, "fff" => 6}

我想加入这两个数据结构中键的原始顺序返回一个哈希到第一个键:

I'd like to join these two data structures to return a hash in the original order of keys to the first keys:

{"ccc" => nil, "ddd" => 4, "ggg" => nil, "aaa" => 1, "bbb" => 2}

物品不对的哈希(如GGG)应该返回为零。
这类似于在Excel的V-查找功能。
这是红宝石。谢谢!

Items NOT in the hash (like "ggg") should return nil. This is analogous to the "v-lookup" function in excel. this is in ruby. Thanks!

推荐答案

隐秘:

Hash[keys.zip(hash.values_at *keys)]

或者时间长一点,少了几分神秘:

Or a bit longer, a bit less cryptic:

keys.map.with_object({}) {|key, memo| memo[key] = hash[key]}

这篇关于加入键的数组的哈希与Excel等VLOOKUP键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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