Hopstream Hopstream - 1 month ago 17
Ruby Question

Convert hash keys to lowercase -- Ruby Beginner

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?

Here is the code I have right now:

CSV.foreach(file, :headers => true) do |row|
Users.create!(row.to_hash)
end


This is failing because the keys are camel case (I've verified this by manually editing the file to make the header row all lowercase).

PS. Also I would love to know why the hell rails takes table field names' case sensitivity into play to begin with?

Answer

You can use something like this:

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

  Users.create!(new_hash)
end

I had no time to test it but, you can take idea of it.
Hope it will help

Comments