Search code examples
ruby-on-railsrubyhashkeytransform

transform_keys for an array of hashes


I have the following array of hashes and I want to use transform_keys to strip the beginning of each key using a regex:

array_of_hashes = [{"a_0_abc"=>"1",  
  "a_0_def"=>"1",  
  "a_0_hij"=>"1",},  
 {"a_1_abc”=>"2",  
  "a_1_def"=>"2",  
  "a_1_hij"=>"2"}]

and I want the following:

transformed_hash_keys = [{"abc"=>"1",  
 "def"=>"1",  
 "hij"=>"1",},  
{"abc"=>"2",  
 "def"=>"2",  
 "hij"=>"2"}]  

I have the following method but it results in array_of_hashes instead of transformed_hash_keys:

def strip  
    s = array_of_hashes.each { |hash| hash.transform_keys { |key| key.sub(/^a_(\d+)_/, '') } }  
end

Can anyone tell me what I'm doing wrong in this method?


Solution

  • transform_keys doesn't operate in place and each returns the original iterator, not the result of the block.

    You could do what you want with map instead of each.

    def strip  
        s = array_of_hashes.map { |hash| hash.transform_keys { |key| key.sub(/^a_(\d+)_/, '') } }  
    end
    

    Or, you could use transform_keys! to modify the contents of array_of_hashes

    def strip  
        s = array_of_hashes.each { |hash| hash.transform_keys! { |key| key.sub(/^a_(\d+)_/, '') } }  
    end