Reputation: 1833
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 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] }
Upvotes: 0
Views: 296
Reputation: 168071
hash.each_with_object({}){|(k, v), h| h[k.sub(/_sub1/, '')] = v if k[/_sub1/]}
Upvotes: 2
Reputation: 9605
This should work:
new_hash = Hash[*hash.keys.map{ |x| x.gusb /_sub\d$/, '' }.zip(hash.values)]
Upvotes: 1