Read TXT file on Rails

Asked

Viewed 356 times

0

I have an application in Ruby on Rails and I need to read a particular file txt which will be sent by the user. After sending the file, the file data will be displayed to the user so that it confirms that the file is correct, and if yes, then save it, the file contains letters that are the answers of a proof and each letter represents a question, for example:

"EEDEBACABDBBADAADEADEAB"

that is to say:

"1 => E, 2 => E, 3 => D, 4 => E"

This file will be sent in format .txt through a form, I hope you can understand!

2 answers

0

First you will have to read character by character and insert it into an array so you can create your hash that auto-increments its key.

answers = []
array = "abc".each_char.map { |char| char }

array.each_with_index do |value, index|
  answers.push("#{index}" => value)
end

puts answers #[{"0"=>"a"}, {"1"=>"b"}, {"2"=>"c"}]

0

respostas = []

File.open("caminho/do/arquivo", "r") do |f|
  f.each_line do |linha|
    (linha.scan /\w/).each_with_index {|val,i| respostas.push(i => val)}
  end
end

Browser other questions tagged

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