How to replace a hash key with another key

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

    you can do

    hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}
    

    This should work for your case!

    0 讨论(0)
  • 2020-12-04 08:10

    Answering exactly what was asked:

    hash = {"_id"=>"4de7140772f8be03da000018"}
    hash.transform_keys { |key| key[1..] }
    # => {"id"=>"4de7140772f8be03da000018"}
    

    The method transform_keys exists in the Hash class since Ruby version 2.5.

    https://blog.bigbinary.com/2018/01/09/ruby-2-5-adds-hash-transform_keys-method.html

    0 讨论(0)
  • 2020-12-04 08:14

    If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:

    h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }
    

    The k[1, k.length - 1] bit grabs all of k except the first character. If you want a copy, then:

    new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]
    

    Or

    new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }
    

    You could also use sub if you don't like the k[] notation for extracting a substring:

    h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
    Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
    h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
    

    And, if only some of the keys have the underscore prefix:

    h.keys.each do |k|
      if(k[0,1] == '_')
        h[k[1, k.length - 1]] = h[k]
        h.delete(k)
      end
    end
    

    Similar modifications can be done to all the other variants above but these two:

    Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
    h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
    

    should be okay with keys that don't have underscore prefixes without extra modifications.

    0 讨论(0)
  • 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"}
    
    0 讨论(0)
  • 2020-12-04 08:15
    hash[:new_key] = hash.delete :old_key
    
    0 讨论(0)
提交回复
热议问题