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

后端 未结 7 1437
广开言路
广开言路 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:39

    i assume you want to change the hash keys without changing the values:

    hash = {
       "nr"=>"123",
       "name"=>"Herrmann Hofreiter",
       "pferd"=>"010 000 777",
       "land"=>"hight land"
    }
    header = ["aa", "bb", "cc", "dd"]
    new_hash = header.zip(hash.values).to_h
    

    Result:

    {
       "aa"=>"123",
       "bb"=>"Herrmann Hofreiter",
       "cc"=>"010 000 777",
       "dd"=>"high land"
    }
    

提交回复
热议问题