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?
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.
I find this approach more elegant:
hash_with_camelcase_keys.to_a.map { |pair| [pair.first.downcase, pair.last] }.to_h
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"}
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
Ruby 1.9 provides quite a nice way to achieve this, using each_with_object to avoiding initialising a temporary variable.
CSV.foreach(file, :headers => true) do |row|
new_hash = row.each_with_object({}) do |(k, v), h|
h[k.downcase] = v
end
Users.create!(new_hash)
end
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