How to replace a hash key with another key

后端 未结 11 1495
青春惊慌失措
青春惊慌失措 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:14

    For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:

    hash1 = { '_id' => 'random1' }
    hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
    hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }
    
    hash1.transform_keys { |key| key.delete_prefix('_') }
    # => {"id"=>"random1"}
    hash2.transform_keys { |key| key.delete_prefix('old_') }
    # => {"first"=>"123456", "second"=>"234567"}
    hash3.transform_keys { |key| key.delete_suffix('_com') }
    # => {"first"=>"google.com", "second"=>"amazon.com"}
    

提交回复
热议问题