Convert hash keys to lowercase — Ruby Beginner

后端 未结 9 2141
终归单人心
终归单人心 2020-12-17 19:51

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?

9条回答
  •  感情败类
    2020-12-17 20:34

    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.

提交回复
热议问题