将哈希键转换为小写——Ruby 初学者 [英] Convert hash keys to lowercase -- Ruby Beginner

查看:32
本文介绍了将哈希键转换为小写——Ruby 初学者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表字段名称是小写的,而我从 CSV 文件中得到的字段名称是驼峰式的.无论如何,我可以将散列数组的键转换为小写吗?

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).

附注.我也很想知道为什么地狱 Rails 一开始就需要表字段名称的区分大小写?

PS. Also I would love to know why the hell rails takes table field names' case sensitivity into play to begin with?

推荐答案

你可以这样使用:

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

这篇关于将哈希键转换为小写——Ruby 初学者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆