I think you have understood the file format very literally, I imagine it must be something like:
{number_id}, {task}, {fact?}
The first being an integer, the second a string and the third a Boolean value {true, false}.
I leave here some clues to a possible implementation of the methods, assuming what I have just commented.
So, we could create the first method like:
def load_tasks(file)
lineas = File.readlines(file) #lectura del fichero de texto por líneas
sol = []
lineas.each do |linea|
ind = 0 # variable de índice en la línea
linea.each_char do |car|
if car == ','
return "Error, formato incorrecto: primero se debe introducir un número entero" if ind == 0
hash = { "id" => linea[0,ind].to_i, "name" => "", "done"=> "" }
sol.push(hash)
ind = 0 # reseteamos índice
break # salida de la línea actual
end
ind += 1
end
end
return sol
end
p load_tasks("contenido.txt") #probado con la misma entrada que das de ejemplo
The code would give the following output:
= >
[{"id" = > 1, "name" = > "", "done" = > ""}, {"id" = > 2, "name" = > "", "done" = > ""}]
Thus the first field "id" would be processed.
Similarly, the following fields could be processed.
Good technique would encapsulate them in different methods, for example the first argument could be a method called read_number that read the number to the comma, then another would come: read_string that could read the task to the comma, and in the same way the third field.
The second method requested is much more elementary, a simple way to do it could be:
File.open(fichero, "w") do |file|
file.write(sol[0].["id"].to_s)
end
We assume that file contains the name of the file and in sun array are the hashes to be saved.
With the previous code, we would have written the first element of the sun array, which is a hash, the value assigned to the "id" field (following the example, it would be a "1").
Just modify the code so that all the elements of the array are scanned and all the fields of the hash are written, separated by commas in the file.
I hope it helps. Health