Convert hash keys to lowercase — Ruby Beginner

后端 未结 9 2170
终归单人心
终归单人心 2020-12-17 19:51

My table field names are lowercase and the field names I get from CSV files are camelcase. Is there anyway I can convert the keys of an array of hashes to lowercase?

9条回答
  •  不知归路
    2020-12-17 20:44

    I would add the hash directly, more efficient than merge! because you're not creating a new hash for every pair.

    CSV.foreach(file, :headers => true) do |row|
      new_hash = {}
      row.to_hash.each_pair do |k,v|
       new_hash[k.downcase] = v 
      end
    
      Users.create!(new_hash)
    end
    

提交回复
热议问题