Convert hash keys to lowercase — Ruby Beginner

后端 未结 9 2137
终归单人心
终归单人心 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:49

    I found that this solution is significantly faster and a bit more "Rubyish".

    CSV.foreach(file, :headers => true) do |row|
      new_hash = Hash[row.to_hash.map { |k, v| [k.downcase, v] }]
      Users.create!(new_hash)
    end
    
    0 讨论(0)
  • 2020-12-17 20:49

    You could consider using underscore instead of downcase because this would also transform the CamelCase to camel_case notation, which is more Rubylike.

    My personal preferences goes to using deep_transform_keys: hash.deep_transform_keys{|key| key.underscore.to_sym }

    As transform_keys do not traverse the whole hash.

    0 讨论(0)
  • 2020-12-17 20:54

    Since this was tagged with Rails.

    With ActiveSupport starting vom version 3.0 you can use a HashWithIndifferentAccess.

    That will allow lower/uppercase/symbol writing to access the keys or your Hash.

    my_hash = { "camelCase": "some value" }
    my_hash.with_indifferent_access[:camelcase] # 'some value'
    my_hash.with_indifferent_access['camelcase'] # 'some value'
    my_hash.with_indifferent_access['camelCase'] # 'some value'
    my_hash.with_indifferent_access['CAMELCASE'] # 'some value'
    

    ActiveSupport 4.0.2 also introduced this:

    my_hash.deep_transform_keys!(&:downcase)
    # or if your hash isn't nested:
    my_hash.transform_keys!(&:downcase)
    
    0 讨论(0)
提交回复
热议问题