How to change all the keys of a hash by a new set of given keys

后端 未结 7 1436
广开言路
广开言路 2020-12-04 19:04

How do I change all the keys of a hash by a new set of given keys?

Is there a way to do that elegantly?

7条回答
  •  半阙折子戏
    2020-12-04 19:57

    h = { 'foo'=>1, 'bar'=>2 }
    key_map = { 'foo'=>'foozle', 'bar'=>'barzle' }
    
    h.each_with_object({}) { |(k,v),g| g[key_map[k]]=v }
      #=> {"foozle"=>1, "barzle"=>2}
    

    or

    h.reduce({}) { |g,(k,v)| g.merge(key_map[k]=>v) }
      #=> {"foozle"=>1, "barzle"=>2} 
    

提交回复
热议问题