2015-01-12 32 views
0

我必須在具有字符串值表中的列堅持值映射表列:與上創建和Rails的更新

arr = ["First Name", "Last Name", "location", "Description"]

我需要每個值依次映射到信:

["A", "B", "C", "D"]

這些字母是不是表的一部分,並沒有定義,但我對上述ARR創建一個小的哈希傾斜,除非有更好的建議?

我需要能夠將每個字母映射到arr中的對應值,並且當arr在視圖中更新時,每個字母應該在arr中對應。例如,如果從arr中刪除「First Name」,那麼第一個應該是「B」,或者如果「位置」被刪除,則新陣列應該是「A」,「B」,「D 」。意義上,在創建或更新時,字母應始終映射到arr中的相應值。我希望我有道理?

非常感謝。

+1

你能澄清這一點:*等等,當用戶創建或更新ARR它堅持*? – mikej

回答

1

例如,你有

arr = ["First Name", "Last Name", "location", "Description"] 
arr_hash= Hash.new 

and yout have a instance for 
@client =Client.first 


hash[0] = [] 
hash[0] << arr 

hash[1] = [] 
hash[1] << @client 

多....

0

你可以用對哈希,然後再刪除不存在於更新數組的鍵。

arr = ["First Name", "Last Name", "location", "Description"] 
arr2 = ["A", "B", "C", "D"] 

result = Hash[arr.zip(arr2)] 
# => {"First Name"=>"A", "Last Name"=>"B", "location"=>"C", "Description"=>"D"} 

# update original arr like: 
arr = ["Last Name", "location", "Description"] 

result.delete_if { |k, _| !arr.include?(k) } 
# => {"Last Name"=>"B", "location"=>"C", "Description"=>"D"} 
+0

謝謝@rastasheep。不是我所需要的。處理其他解決方案。 –