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

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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!

回答1:

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]} 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!