2016-03-10 264 views
0

我有以下嵌套哈希嵌套哈希 - 紅寶石

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寶石)

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:沒有將符號隱式轉換爲整數)

我需要轉換把數組中的每一項都放回到哈希中,還是有更接近這個的更清晰的方法?

感謝

回答

2

你,你所面臨的問題的假設是不相關的實際問題。

select條件有誤(它甚至沒有條件,它是一個賦值)。此外,應明確地定義,其中是鍵(key),並且其中對應於它元件(_ - 強調裝置,您沒有在塊的上下文使用的話):

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

道歉,錯字意味着我錯過了我的'testy_user方法'花括號 – Richlewis

+1

謝謝你的幫助和澄清我的錯誤 – Richlewis