2017-05-09 60 views
0

這是我的代碼,我嘗試創建一個帶有標題的散列作爲鍵和帶有值的散列數組,但結果不會在循環後保留數據,相反,結果[key]起作用normaly。在奇怪的行爲循環中創建一個散列

def programacao 
    result = Hash.new([]) 
    header = nil 
    csv_each_for(file_to('programacao/9')).each do |row| 
     next if row[0].nil? 

     if row[0].start_with?('#') 
     header = row[0] 
     next 
     end 
     # puts "HEADER #{header}/ROW: #{row[0]}" 
     result[header] << ({ 
          horario: row[0], 
          evento: row[1], 
          tema: row[2], 
          palestante: row[3], 
          instituicao: row[4], 
          local: row[5] 
     }) 
     binding.pry 
    end 
    result 
    end 

第一次迭代:

[1] pry(#<Programacao>)> result 
=> {} 

但導致[讀者]

[3] pry(#<Programacao>)> result[header] 
=> [{:horario=>"09:00 - 9:50", 
    :evento=>"Palestra", 
    :tema=>"Reforma da Previdência", 
    :palestante=>"Dr. Álvaro Mattos Cunha Neto", 
    :instituicao=>"Advogado - Presidente da Comissão de Direito Previdenciário", 
    :local=>"OAB"}] 

第二次迭代:

[1] pry(#<Programacao>)> result 
=> {} 

標準鋼廠普通

[2] pry(#<Programacao>)> result[header] 
=> [{:horario=>"09:00 - 9:50", 
    :evento=>"Palestra", 
    :tema=>"Reforma da Previdência", 
    :palestante=>"Dr. Álvaro Mattos Cunha Neto", 
    :instituicao=>"Advogado - Presidente da Comissão de Direito Previdenciário", 
    :local=>"OAB"}, 
{:horario=>"9:00 -10:00", :evento=>"Solenidade de abertura do Estande", :tema=>nil, :palestante=>"Direção/Coordenações", :instituicao=>nil, :local=>"Faculdade Católica do Tocantins"}] 

我的錯誤在哪裏?

+0

你能分享你的csv嗎? –

回答

2

我不完全理解你的問題,因爲你還沒有提供Minimal, Complete, and Verifiable example。 (什麼是csv_each_for?什麼是file_to?什麼是你輸入CSV?如果提供所有這些信息是不必要的,那麼可以爲您提供一個最小例子嗎?)

不過,我相信你的問題的癥結是這條線:

result = Hash.new([]) 

相反,你應該使用:

result = Hash.new { |hash, key| hash[key] = [] } 

這是因爲,在the ruby docs提到的,你需要創建一個新的每次默認對象。

這是一個common gotcha。正是由於這個錯誤,你看到了奇怪的行爲,其中result == {}但是result[something] == [{:horario=>"09:00 - 9:50", ...}]

+0

工作正常! :) 謝謝! –