hash = {
"key1_sub1" => [0, 1, 2],
"key2_sub2" => [1, 12],
"key3_sub1" => [4, 5, 6]
}
是否有一个班轮会给我一个新的哈希
它找到与原始哈希中的键模式“_sub1”匹配的哈希值,通过删除“_sub1”来构造新键
new_hash = { "key1" => [0, 1, 2], "key3" => [4, 5, 6] }
答案 0 :(得分:2)
hash.each_with_object({}){|(k, v), h| h[k.sub(/_sub1/, '')] = v if k[/_sub1/]}
答案 1 :(得分:1)
这应该有效:
new_hash = Hash[*hash.keys.map{ |x| x.gusb /_sub\d$/, '' }.zip(hash.values)]