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?
Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase : "hello James!". downcase #=> "hello james!"
The contents of a certain hash can be replaced in Ruby by using the replace() method. It replaces the entire contents of a hash with the contents of another hash.
In Ruby, we use the downcase method to convert a string to lowercase. This method takes no parameters and returns the lowercase of the string that calls it. It returns the original string if no changes are made. Note: This method does not affect the original string.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With