Hopstream Hopstream - 1 year ago 206
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|

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 Source

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}) 


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download