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:
and a hash
I'd like to join these two data structures to return a hash in the original order of keys to the first keys:
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:
Or a bit longer, a bit less cryptic:
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]}
相关文章推荐
- How to combine the value of multiple hashes within an array by the same key
- How to sort an array of hashes into hashes with multiple values for a key?
- Err:The "." operator was supplied with an index value of type "java.lang.String" to be applied to a List or array
- How to limit an array of similar hashes to those that have more than one of the same key:value pair
- How to sum values in an array with different hash
- Python-numpy逻辑报错:The truth value of an array with more than one element is ambiguous
- Iterate through array, for each item with key collect value and make new array with key and array of
- The "." operator was supplied with an index value of type "java.lang.String" to be applied to a List
- how to merge array of hash based same keys in ruby?
- Obtain Key from a Hash of Arrays using array value
- Python-numpy逻辑报错:The truth value of an array with more than one element is ambiguous. Us
- ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.al
- Convert array of key value object to object of the key values (ruby)
- How do I sort an array of hashes by a value in the hash?
- How do I sort an array of hashes by a value in the hash?
- Array to hash with multiple keys
- The web application created a ThreadLocal with key of type [null] (value [com.opensymphony.xwork2.inject.ContainerImpl$10@1807b9
- 严重: A web application created a ThreadLocal with key of type [null] (value [com.sun.faces.config.Con
- 转载:how to automate Microsoft Excel and return the values from a multi-cell range to an array
- There is integer array like {1,2,4,5,6,1,2,4,3,5,7,2,1}. I want to find the possible combination of pair which sum is 4.