How to replace a hash key with another key

后端 未结 11 1500
青春惊慌失措
青春惊慌失措 2020-12-04 07:36

I have a condition where, I get a hash

  hash = {\"_id\"=>\"4de7140772f8be03da000018\", .....}

and I want this hash as

         


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 08:02

    Previous answers are good enough, but they might update original data. In case if you don't want the original data to be affected, you can try my code.

     newhash=hash.reject{|k| k=='_id'}.merge({id:hash['_id']})
    

    First it will ignore the key '_id' then merge with the updated one.

提交回复
热议问题