Convert hash keys to lowercase -- Ruby Beginner

Since this was tagged with Rails.

With ActiveSupport starting vom version 3.0 you can use a HashWithIndifferentAccess.

That will allow lower/uppercase/symbol writing to access the keys or your Hash.

my_hash = { "camelCase": "some value" }
my_hash.with_indifferent_access[:camelcase] # 'some value'
my_hash.with_indifferent_access['camelcase'] # 'some value'
my_hash.with_indifferent_access['camelCase'] # 'some value'
my_hash.with_indifferent_access['CAMELCASE'] # 'some value'

ActiveSupport 4.0.2 also introduced this:

my_hash.deep_transform_keys!(&:downcase)
# or if your hash isn't nested:
my_hash.transform_keys!(&:downcase)

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


You can just use the header_converters option with CSV:

CSV.foreach(file, :headers => true, :header_converters => lambda { |h| h.try(:downcase) }) do |row|
  Users.create!(row.to_hash)
end

Important to put the .try in there since an empty header will throw an exception. Much better (and faster) than doing this on every row.


You can simple do

hash.transform_keys(&:downcase)

to change hash keys to lowercase, or you can also transform hash values to lowercase or upper case as per your requirement.

hash.transform_values(&:downcase) or hash.transform_values(&:upcase)

hash = {:A=>"b", :C=>"d", :E=>"f"}
hash.transform_keys(&:downcase)
=> {:a=>"b", :c=>"d", :e=>"f"}