2010-09-21 89 views
0

我從一個哈希檢索信息快速的問題,這裏是代碼至今:檢索從哈希信息散列內 - 紅寶石

permits_sheet.each do |row| 
    rate_type = row[0].to_s #Converts the rate type (title) to a string 
    row.shift #Removes the title from hash so it's not added to values 
    row.each do |values| 
    split_value = values.split ('=') #References relations from an excel sheet pulled in earlier. EG: T=2324, W=8633 
    (@@permits_hash[rate_type] ||= []) << {split_value[0].to_s => split_value[1]} #Multiple values exist within each title 
    end 
end 

puts @@permits_hash['R']['T'] #In this example I'm searching for the hash key of T under the R title. I expected it to return the 2324 from the example above. 

當試圖以這種方式它會導致一個錯誤檢索信息。我確信我只是做了一些愚蠢的事情,但是任何幫助都將不勝感激(在相當一段時間裏還沒有使用過Ruby)。

感謝您的幫助!

+0

這將是有益的,如果你能發佈的錯誤信息。 – 2010-09-21 19:32:09

+0

Test.rb:117:in'[]':無法將字符串轉換爲整數(TypeError) 所有內容都已轉換爲字符串,所以我遇到了一些排查問題的問題。 – 2010-09-21 19:34:30

+0

您正在使用字符串爲數組建立索引。 – yxhuvud 2010-09-21 19:41:26

回答

2

如何不將哈希存儲在數組中,而是像嵌套哈希?

(@@permits_hash[rate_type] ||= {})[split_value[0].to_s]=split_value[1]] 

不是說它有助於可讀性,但我實際上認爲你可以將兩個循環寫成一行。

@@permits_hash=Hash.new 
row=["title","k1=v2","k2=v2","k3=v3"] 
# Here's the line replacing the two loops 
(@@permits_hash[row.shift] ||= {}).update(Hash[*row.map{|v| v.split("=")}.flatten]) 

>> @@permits_hash
=> {"title"=>{"k1"=>"v2", "k2"=>"v2", "k3"=>"v3"}}

+0

你先生,是個紳士和學者。這正是我一直在尋找的,但我一直盯着屏幕這麼久,我只是不記得如何正確地做到這一點。 再次感謝您的幫助! – 2010-09-21 19:56:12

+0

謝謝,還添加了一行。 – 2010-09-21 20:17:03

+2

@Ruby新手:如果喬納斯解決了你的問題(因爲它出現),你會很高興通過點擊答案左邊的複選標記來接受他的答案。 – 2010-09-21 20:18:14