2017-05-09 55 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

工作正常! :) 谢谢! –