您的位置:首页 > 产品设计 > UI/UE

Joining an array of keys to a hash with key value pairs like excel vlookup

2014-07-05 20:14 561 查看
I've got an unsorted array of keys like this:

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

and a hash

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}

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!

Cryptic:

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]}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐