Search code examples
rubyhashlowercase

how to change hash keys in the lower case using ruby


Given hash with nested documents:

myHash = {
  "MemberId"=>"ABC0001", 
  "MemberName"=>"Alan", 
  "details"=>[
    {"LineNumber"=>"4.1", "Item"=>"A0001", "Description"=>"Apple"}, 
    {"LineNumber"=>"5.1", "Item"=>"A0002"}, 
    {"LineNumber"=>"6.1", "Item"=>"Orange"}
  ]
}

I want to change it so it will look like:

{
  "memberid"=>"ABC0001", 
  "membername"=>"Alan", 
  "details"=>[
    {"linenumber"=>"4.1", "item"=>"A0001", "description"=>"Apple"}, 
    {"linenumber"=>"5.1", "item"=>"A0002"}, 
    {"linenumber"=>"6.1", "item"=>"Orange"}
  ]
}

In other words, I want to change to lower case if any in the hash key. I understand I'll have to iterate through the hash and use downcase method. If there any easy way of doing this in ruby?


Solution

  • class Hash
      def downcase_key
        keys.each do |k|
          store(k.downcase, Array === (v = delete(k)) ? v.map(&:downcase_key) : v)
        end
        self
      end
    end
    
    myHash.downcase_key