Adding Array in a hash during a loop does not persist the data until the end

0

I've come to ask you for help because I can not see where I'm wrong, certainly bullshit. I am reading a csv and structuring this data in a Hash , where I have header as key and array hashes as value.

 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]
      })
    end
    result
  end

There's the odd point, if I stop running during loop and check the value of result , it will be empty, but if I access a specific key it is being persisted.

First iteration:

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

mas result [reader]

[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"}]

Second interaction:

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

While with header

[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"}]
    
asked by anonymous 09.05.2017 / 14:55

1 answer

0

Just replace

result = Hash.new([])

by

result = Hash.new { |hash, key| hash[key] = [] }
    
09.05.2017 / 16:21