嵌套哈希 - Ruby

时间:2016-03-10 14:17:43

标签: arrays ruby hash

我有以下嵌套哈希

def testy_user
 {
  search_templates: { 
     profile_1: { default_search_form: 'simple', name: 'Automation Profile', default_profile: 'yes', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_2: { default_search_form: '', name: 'Potential Links', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_3: { default_search_form: '', name: 'Insolvency', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_4: { default_search_form: '', name: 'Mortality', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_5: { default_search_form: '', name: 'Mortality', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_6: { default_search_form: '', name: 'PRS', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_7: { default_search_form: '', name: 'Neighbour', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_8: { default_search_form: '', name: 'Smartlinks', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_9: { default_search_form: '', name: 'Property', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' },
     profile_10: { default_search_form: '', name: 'Occupants', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }
     }
 }
end

我正在整理一些逻辑,它将遍历每个“配置文件”并写入我的数据库(使用Mysql gem)

testy_user[:search_templates].select { |p| p=[/^profile_/] }.each do |template|
  statement = @db.prepare('INSERT INTO profile (fk_user_id, default_search_form, name, default_profile, ref_required, fk_search_type_id) VALUES(?,?,?,?,?,?)')
  statement.execute(@user_id, template[:default_search_form], template[:name], template[:default_profile], template[:ref_required], template[:fk_search_type_id])
end

因为我现在处于这个循环中,每个template都是一个数组,我不能再将这些键作为符号访问(我得到TypeError:没有将Symbol隐式转换为整数)

我是否需要将数组中的每个项目转换回哈希值,或者是否有更简洁的方法来接近它?

由于

1 个答案:

答案 0 :(得分:2)

您对所面临问题的假设与实际问题无关。

select条件错误(它甚至不是条件,它是作业)。此外,您应该明确定义键在哪里( ie key )以及与其对应的元素( ie _ - 下划线表示,你没有在块的上下文中使用它):

testy_user[:search_templates].select{|key, _| key =~ /^profile_/ }.each do |_, template|
  <your code>
end