construct a new hash with different keys
hash = {
"key1_sub1" => [0, 1, 2],
"key2_sub2" => [1, 12],
"key3_sub1" => [4, 5, 6]
}
is there a one liner will return me a new hash
it find the hash开发者_JAVA技巧 value matching the key pattern "_sub1" in the original hash, construct the new key by removing "_sub1"
new_hash = { "key1" => [0, 1, 2], "key3" => [4, 5, 6] }
hash.each_with_object({}){|(k, v), h| h[k.sub(/_sub1/, '')] = v if k[/_sub1/]}
This should work:
new_hash = Hash[*hash.keys.map{ |x| x.gusb /_sub\d$/, '' }.zip(hash.values)]
精彩评论