I have the following file .txt
, which I opened with File.Open("productos.txt", "r")
.
The thing is that this file comes in the following format.
Producto1, 10, 15, 21
Producto2, 20, 0, 3
Producto3, 4, 8, 0
Producto8, 1, 2, NR
Producto12, NR, 2, NR
And I have to add the numbers of the first column, it is also complicated for me since the last number of the column is a string and I have to transform it.
In short, I have to do that sum from column , and I can't find a way to do that separation or get to that position .
Considering that the file is not very big (as in your example), I would do the following:
In code it would look like this:
In case the file is very large, you could choose to use
File.foreach
instead ofFile.read
to read the file line by line; for instance:It is important to note that when applying
to_i
to a string that does not start with a number , the result is always0
.Examples: