Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 480
Hopstream Avatar asked Nov 02 '11 12:11

Hopstream


People also ask

How do you change uppercase to lowercase in Ruby?

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase : "hello James!". downcase #=> "hello james!"

How do I change a hash value in Ruby?

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.

How do you change case in Ruby?

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.


1 Answers

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"}
like image 51
Touseef Murtaza Avatar answered Sep 20 '22 15:09

Touseef Murtaza