Addition of Array to a Hash during a loop does not persist the data until the end

Asked

Viewed 19 times

0

I had to come to you for help because I cannot see where I am wrong, certainly a nonsense. I am reading a csv and structuring this data into a Hash, where I have a header as key and a array of hashes as a 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 goes the odd spot, if I stop the execution during the 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
=> {}

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

1 answer

0

It was enough to replace

result = Hash.new([])

for

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.