File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -923,6 +923,29 @@ describe "Hash" do
923923    h2.should eq({" 1a"   => " a"  , " 2b"   => " b"  , " 3c"   => " c"  })
924924  end 
925925
926+   describe " transform_keys!"   do 
927+     it " transforms keys in place"   do 
928+       h =  {1  => " a"  , 2  => " b"  , 3  => " c"  }
929+ 
930+       h.transform_keys! { |x | x +  1  }.should be(h)
931+       h.should eq({2  => " a"  , 3  => " b"  , 4  => " c"  })
932+     end 
933+ 
934+     it " does nothing when empty hash"   do 
935+       h =  {} of Int32  => String 
936+ 
937+       h.transform_keys! { |x | x +  1  }
938+       h.should be_empty
939+     end 
940+ 
941+     it " transforms keys with values included"   do 
942+       h =  {" 1"   => " a"  , " 2"   => " b"  , " 3"   => " c"  }
943+ 
944+       h.transform_keys! { |k , v | " #{ k } #{ v } "   }
945+       h.should eq({" 1a"   => " a"  , " 2b"   => " b"  , " 3c"   => " c"  })
946+     end 
947+   end 
948+ 
926949  it " transforms values"   do 
927950    h1 =  {" a"   => 1 , " b"   => 2 , " c"   => 3 }
928951
Original file line number Diff line number Diff line change @@ -1755,6 +1755,24 @@ class Hash(K, V)
17551755    end 
17561756  end 
17571757
1758+   #  Destructively transforms all keys using a block. Same as transform_keys but modifies in place.
1759+   #  The block cannot change a type of keys.
1760+   #  The block yields the key and value.
1761+   # 
1762+   #  ```
1763+   #  hash = {"a" => 1, "b" => 2, "c" => 3}
1764+   #  hash.transform_keys! { |key| key.upcase }
1765+   #  hash # => {"A" => 1, "B" => 2, "C" => 3}
1766+   #  hash.transform_keys! { |key, value| key * value }
1767+   #  hash # => {"a" => 1, "bb" => 2, "ccc" => 3}
1768+   #  ```
1769+   def  transform_keys !(& block : K , V  - >  K ) : self 
1770+     copy =  self .transform_keys(& block)
1771+     self .clear()
1772+     self .merge!(copy)
1773+     self 
1774+   end 
1775+ 
17581776  #  Returns a new hash with the results of running block once for every value.
17591777  #  The block can change a type of values.
17601778  #  The block yields the value and key.
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments