user612308
user612308

Reputation: 1833

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

Answers (2)

sawa
sawa

Reputation: 168071

hash.each_with_object({}){|(k, v), h| h[k.sub(/_sub1/, '')] = v if k[/_sub1/]}

Upvotes: 2

dnch
dnch

Reputation: 9605

This should work:

new_hash = Hash[*hash.keys.map{ |x| x.gusb /_sub\d$/, '' }.zip(hash.values)]

Upvotes: 1

Related Questions